Unit-l
Java EE Architecture (Containers, Technologies, CGI-1.7):
1.1) What is a Java Enterprise Application? Explain its architecture?
1. Definition :
i) Enterprise applications - Large-scale, distributed, multi-tier applications designed for business
needs.
ii) Java Enterprise Edition (JEE) - Provides APIs and runtime environment to build secure,
scalable, and robust enterprise applications.
2. Features of Enterprise Applications :
i) Scalability - Supports growth in users and data.
ii) Security - Provides authentication, authorization, and encryption.
iii) Reliability - Ensures fault tolerance and consistency.
iv) Portability - Runs on multiple platforms using JVM.
v) Integration - Supports web services, messaging, and databases.
vi) Reusability - Encourages component-based development for code reuse.
3. Architecture of Java Enterprise Applications :
i) Client Tier - End-user interface (browser, desktop app, mobile app).
ii) Web Tier - Handles requests and responses using Servlets, JSP, JSF.
iii) Business Tier - Contains business logic with EJB (Enterprise JavaBeans), POJOs, or Spring
beans.
iv) Enterprise Information System (EIS) Tier - Database servers, ERP, and legacy system
integration.
4. Example :
i) Online Shopping System - Client tier (mobile app/browser), Web tier (servlets/JSP), Business
tier (payment & order logic), EIS tier (database storing users, products, and transactions).
1.2) What is Java Enterprise Edition (Java EE)? Explain its architecture?
1. Definition :
i) Java EE - A set of specifications and APIs built on top of Java SE for developing enterprise-level,
distributed, and multi-tier applications.
ii) Provides - Tools, APIs, and runtime environment for scalable, portable, and secure business
applications.
2. Features of Java EE :
i) Component-based - Uses Servlets, JSP, EJB, and JSF for modular development.
ii) Scalability - Supports large number of users and transactions.
iii) Security - Offers authentication, authorization, and secure communication.
iv) Interoperability - Integrates with databases, legacy systems, and web services.
v) Portability - Runs across any compliant application server.
vi) Productivity - Reduces development time with built-in services like JNDI, JMS, JPA.
3. Java EE Architecture (Multi-Tier) :
i) Client Tier - Web browsers, desktop apps, or mobile apps sending requests.
ii) Web Tier - Manages client requests using Servlets, JSP, JSF.
iii) Business Tier - Contains business logic with EJB, POJOs, or Spring beans.
iv) Enterprise Information System (EIS) Tier - Handles persistence with databases, ERP, or
external systems.
4. Example :
i) Online Banking System - Client tier (browser/mobile app), Web tier (servlets/JSP), Business tier
(transaction logic), EIS tier (database for accounts and transactions).
1.3) Write a note on Multi-Tier Application Architecture?
1. Definition :
i) Multi-Tier Architecture - A software design pattern that divides applications into multiple logical
layers (tiers).
ii) Purpose - Improves scalability, maintainability, and separation of concerns.
2. Features :
i) Separation of Concerns - Each tier handles a specific responsibility (client, logic, data).
ii) Scalability - Easy to scale tiers independently as demand grows.
iii) Flexibility - Tiers can be modified or replaced without affecting others.
iv) Reusability - Components of each tier can be reused across applications.
v) Security - Sensitive data can be secured in back-end tiers.
3. Types of Multi-Tier Architecture :
i) 2-Tier - Client directly communicates with the database (less scalable).
ii) 3-Tier - Client tier, business logic tier, and database tier (most common).
iii) N-Tier - Extension of 3-tier with additional layers like presentation, integration, and services.
4. Example :
i) E-Commerce Application -
a) Client Tier - Web browser or mobile app.
b) Web Tier - JSP/Servlets handling user requests.
c) Business Tier - Payment, order processing, inventory logic.
d) Data Tier - Database storing users, orders, products.
1.4) Explain 2-Tier System Architecture, its advantages, and disadvantages?
1. Definition :
i) 2-Tier Architecture - A client-server model where the client communicates directly with the
database server.
ii) Components - Client tier (user interface) and Data tier (database).
2. Working :
i) Client Tier - Contains user interface and application logic.
ii) Data Tier - Stores and manages data in a database server.
iii) Communication - Client directly sends SQL queries to the database and receives results.
3. Advantages :
i) Simplicity - Easy to design, develop, and maintain.
ii) Performance - Faster communication due to direct client-database interaction.
iii) Cost-effective - Requires fewer hardware and software resources.
iv) Suitable - Best for small-scale applications with limited users.
4. Disadvantages :
i) Scalability - Not suitable for large applications with many users.
ii) Security - Direct client-database communication is less secure.
iii) Maintenance - Changes in database schema affect all clients.
iv) Limited Flexibility - Difficult to integrate with new technologies.
5. Example :
i) Small banking application where client software connects directly to the database.
1.5) Define Java EE Containers and Explain the Various Container Types?
1. Definition :
i) Java EE Container - A runtime environment that manages the execution of Java EE
components (servlets, EJBs, JSPs).
ii) Purpose - Provides system services like lifecycle management, security, transaction handling,
and resource management.
2. Role of Containers :
i) Manage - The lifecycle of components.
ii) Provide - Services like JNDI, transaction, and persistence.
iii) Ensure - Security, scalability, and portability across platforms.
3. Types of Java EE Containers :
i) Web Container -
a) Manages servlets, JSP, and web components.
b) Provides HTTP request/response handling.
ii) EJB (Enterprise JavaBean) Container -
a) Manages business logic components (EJBs).
b) Provides services like transactions, security, and concurrency.
iii) Application Client Container -
a) Supports standalone client applications using Java EE APIs.
b) Provides communication with enterprise components and servers.
iv) Applet Container -
a) Runs inside web browsers to manage Java applets.
b) Provides a secure environment for executing client-side Java code.
4. Example :
i) Web Container - Apache Tomcat managing servlets.
ii) EJB Container - JBoss/WildFly managing enterprise beans.
1.6) What are the Different Technologies Provided by the Java EE Platform?
1. Definition :
i) Java EE - A collection of APIs and services for building distributed, secure, and scalable
enterprise applications.
ii) Purpose - Provides standardized technologies for web, business logic, database, and
messaging.
2. Core Technologies :
i) Servlet & JSP -
a) Servlet - Handles HTTP requests and responses.
b) JSP - Simplifies dynamic web content creation.
ii) JDBC -
a) Provides - Database connectivity.
b) Allows - SQL queries and result handling.
iii) EJB (Enterprise JavaBeans) -
a) Encapsulates - Business logic.
b) Provides - Services like transactions and security.
iv) JMS (Java Message Service) -
a) Enables - Asynchronous communication.
b) Supports - Messaging between distributed components.
v) JPA (Java Persistence API) -
a) Simplifies - Object-relational mapping(ORM).
b) Manages - Data persistence with databases.
vi) JAX-RS / JAX-WS -
a) JAX-RS - For RESTful web services.
b) JAX-WS - For SOAP-based web services.
vii) JavaMail -
a) Used - For sending/receiving emails.
viii) JTA (Java Transaction API) -
a) Manages - Distributed transactions.
ix) JNDI (Java Naming and Directory Interface)-
a) Provides - Naming and directory services.
3. Example :
i) Online Banking Application - Uses Servlets/JSP (UI), EJB (business logic), JDBC/JPA
(database), JMS (notifications), JavaMail (email alerts).
1.7) Write a Short Note on CGI and Explain its Alternatives?
1. Definition :
i) CGI (Common Gateway Interface) - A standard protocol that enables web servers to run
external programs for generating dynamic content.
ii) Purpose - Allows client requests (via web forms) to be processed on the server using scripts or
executables.
2. Features of CGI :
i) Platform Independent - Supports multiple programming languages like C, Perl, Python, and
Shell scripts.
ii) Dynamic Content - Creates customized responses such as form handling, database access, or
report generation.
3. Limitations of CGI :
i) Performance - Each request creates a new process, consuming CPU and memory.
ii) Scalability - Not suitable for high-traffic websites due to heavy resource usage.
iii) Maintenance - Managing large applications with many scripts becomes complex.
4. Alternatives to CGI :
i) Servlets - Java-based, multithreaded, faster than CGI, and widely used in enterprise apps.
ii) JSP (JavaServer Pages) - Allows mixing Java code with HTML for easier development.
iii) [Link] - Microsoft framework offering high performance, built-in security, and better
scalability.
iv) PHP - Open-source, widely supported on servers, best for small to medium web apps.
v) [Link] - Uses event-driven, non-blocking I/O, ideal for real-time scalable apps.
5. Example :
i) In a CGI-based web form submission, each user request spawns a new process to handle data.
ii) In Servlets or [Link], the same request is managed by threads or event loops, making it faster
and more scalable.
Servlets (Life cycle, Package, Task-1.10):
1.8) Explain the Life Cycle of a Servlet with a Diagram?
1. Definition:
i) Servlet - A Java program that runs on the server side, extends server functionality, and
generates dynamic web content.
ii) Servlet Life Cycle - Managed by the Servlet Container (e.g., Tomcat), it defines the process from
creation to destruction of a servlet.
2. Servlet Life Cycle Stages:
i) Loading and Instantiation
a) The servlet class is loaded into memory by the container.
b) An instance of the servlet is created using the default constructor.
ii) Initialization (init() method)
a) Called once when the servlet is first created.
b) Used for initialization tasks like setting up resources (DB connections, configuration
parameters).
iii) Request Handling (service() method)
a) Called for every client request.
b) Determines request type (GET, POST, etc.) and calls appropriate methods (doGet(), doPost(),
etc.).
c) Main logic of request processing and response generation is written here.
iv) Destruction (destroy() method)
a) Called once before the servlet instance is removed from service.
b) Used for releasing resources like closing database connections, stopping background threads,
etc.
3. Diagram:
Servlet Loaded
|
init() called once
|
service() called <---- Handles requests (doGet, doPost, etc.)
|
destroy() called once
4. Example:
i) When a user requests a page, the servlet container loads the servlet (if not loaded), calls init(),
then executes service() for each request, and finally calls destroy() when the server shuts down.
1.9) Write a short note on the [Link] package?
1. Definition:
i) [Link] package - Provides classes and interfaces to define, implement, and manage
Servlets.
ii) Core role - Enables web components (Servlets) to interact with clients through request and
response handling.
2. Key Interfaces:
i) Servlet - Defines the basic methods (init, service, destroy, getServletConfig, getServletInfo) for
all servlets.
ii) ServletRequest - Provides client request information (parameters, attributes, input stream).
iii) ServletResponse - Used to send responses to the client (output stream, writer, content type).
iv) RequestDispatcher - Forwards or includes the content of another resource (Servlet, JSP,
HTML).
v) ServletConfig - Provides servlet configuration details (init parameters, servlet name).
vi) ServletContext - Provides application-level information shared by all servlets in a web app.
3. Key Classes:
i) GenericServlet - An abstract class implementing Servlet and ServletConfig, provides a
framework for creating servlets.
ii) HttpServlet - Extends GenericServlet, simplifies handling of HTTP requests (GET, POST, PUT,
DELETE).
4. Example:
i) A servlet class extending HttpServlet uses [Link] and [Link] packages to
handle HTTP requests and responses in a web application.
1.10) List and explain the tasks that a Servlet can perform?
1. Definition:
i) Servlet - A server-side Java program that handles client requests and generates dynamic
responses.
ii) Tasks - It performs various operations like processing, communication, and response
generation for web applications.
2. Tasks of a Servlet:
i) Process Client Requests - Reads form data, query strings, and request parameters from the
client.
ii) Generate Dynamic Responses - Produces HTML, JSON, XML, or other formats dynamically.
iii) Communicate with Databases - Connects with databases using JDBC to store, retrieve, or
update data.
iv) Maintain Session State - Uses sessions, cookies, or URL rewriting to track user activities
across requests.
v) Share Data - Shares data between multiple servlets or JSPs using attributes, ServletContext,
and RequestDispatcher.
vi) Act as Middleware - Works between client requests and back-end systems (databases, APIs,
services).
vii) Provide Security - Handles authentication, authorization, and secure data transmission.
3. Example:
i) A login servlet - Reads username and password, validates them with the database, maintains
session for the user, and forwards to a welcome page.
JDBC (Architecture, Driver, Statement-1.13):
1.11) What is JDBC? Explain the architecture of JDBC in detail?
1. Definition:
i) JDBC (Java Database Connectivity) - A Java API that allows Java applications to interact with
databases.
ii) Purpose - Provides a standard interface for executing SQL queries and retrieving results
independent of the database.
2. Features of JDBC:
i) Platform Independent - Works with any database using suitable drivers.
ii) SQL Execution - Supports queries, updates, stored procedures.
iii) Connectivity - Provides seamless communication between Java programs and databases.
iv) Standard API - Ensures portability across databases.
v) Extensible - Supports multiple types of drivers for flexibility.
3. JDBC Architecture:
i) Application Layer - Java application that sends SQL requests through JDBC API.
ii) JDBC API - Provides interfaces and classes (Connection, Statement, ResultSet, etc.) to interact
with the database.
iii) JDBC Driver Manager - Manages database drivers, establishes connection between
application and database.
iv) JDBC Driver - Translates JDBC calls into database-specific calls.
v) Database - Backend relational database (MySQL, Oracle, PostgreSQL, etc.) that stores and
manages data.
4. Diagram:
Java Application JDBC API Driver Manager JDBC Driver Database
5. Example:
i) A banking system uses JDBC to connect Java application to MySQL for account transactions.
1.12) What is a JDBC Driver? List and explain each of the four JDBC driver types?
1. Definition:
i) JDBC Driver - A software component that enables Java applications to connect and interact
with databases.
ii) Function - Translates JDBC API calls into database-specific operations.
2. Role of JDBC Driver:
i) Establishes - Connection between Java program and database.
ii) Executes - SQL queries and updates.
iii) Retrieves - Results from the database.
iv) Ensures - Database independence by following JDBC standards.
3. Types of JDBC Drivers:
i) Type 1: JDBC-ODBC Bridge Driver
a) Uses - ODBC driver to communicate with the database.
b) Advantage - Simple implementation, supports multiple databases.
c) Disadvantage - Slow performance, requires ODBC installation, platform dependent.
ii) Type 2: Native-API Driver
a) Converts - JDBC calls into database-specific native API calls.
b) Advantage - Better performance than Type 1.
c) Disadvantage - Needs native client libraries, less portable.
iii) Type 3: Network Protocol Driver
a) Converts - JDBC calls into a database-independent protocol via middleware server.
b) Advantage - Fully portable, no client libraries required.
c) Disadvantage - Requires middleware server, increases complexity.
iv) Type 4: Thin Driver (Pure Java Driver)
a) Converts - JDBC calls directly into database-specific protocol using Java.
b) Advantage - Platform independent, best performance, widely used.
c) Disadvantage - Requires different driver for each database.
1.13) What is a JDBC Statement object? Explain its three types?
1. Definition:
i) JDBC Statement - An interface in JDBC used to send SQL commands to the database and
retrieve results.
ii) Purpose - Provides methods for executing queries (SELECT) and updates (INSERT, UPDATE,
DELETE).
2. Role of Statement:
i) Sends - SQL queries to the database.
ii) Executes - Queries or updates and returns results.
iii) Manages - Interaction between Java application and database.
3. Types of Statement Objects:
i) Statement
a) Used - For executing simple SQL queries without parameters.
b) Example - SELECT * FROM students;
c) Limitation - Cannot handle dynamic values efficiently, prone to SQL injection.
ii) PreparedStatement
a) Precompiled - SQL query with placeholders (?) for parameters.
b) Advantage - Faster execution, prevents SQL injection, reusable.
c) Example - SELECT * FROM students WHERE id = ?;
iii) CallableStatement
a) Used - For executing stored procedures in the database.
b) Advantage - Supports IN, OUT, and INOUT parameters, allows complex business logic.
c) Example - CALL getStudentDetails(?);
4. Example Usage:
i) Statement - [Link]("SELECT * FROM users");
ii) PreparedStatement - [Link](1, 101); [Link]();
iii) CallableStatement - [Link](2, [Link]); [Link]();
Practical (Steps, Coding-1.16):
1.14) What are the steps to create a Web Application using an IDE like NetBeans?
1. Definition:
i) Web Application - A Java-based program that runs on a server and is accessed via a web
browser.
ii) NetBeans IDE - An integrated development environment that provides tools to easily develop,
test, and deploy Java web applications.
2. Steps to Create a Web Application in NetBeans:
i) Create New Project
a) Open NetBeans File New Project.
b) Select "Java Web" "Web Application".
ii) Configure Project
a) Enter project name and location.
b) Choose server (e.g., Apache Tomcat, GlassFish).
c) Set Java EE version.
iii) Set Project Structure
a) NetBeans creates folders: src, web, WEB-INF.
b) web folder stores JSP, HTML, CSS, JS.
c) WEB-INF contains [Link] and libraries.
iv) Add Servlets / JSPs
a) Right-click New Servlet (for server-side logic).
b) Right-click New JSP/HTML (for UI pages).
v) Configure Deployment Descriptor
a) Update [Link] with servlet mapping.
b) Define welcome page if needed.
vi) Build and Run Application
a) Clean and build the project.
b) Run project launches on server (Tomcat/GlassFish).
c) Browser opens automatically to show output.
3. Example:
i) Project - "StudentApp".
ii) Servlet - Handles form input (student details).
iii) JSP - Displays result in browser.
1.15) Write a servlet program that accepts user details from a form and stores them in a
database using JDBC?
// [Link]
<form action="RegisterServlet" method="post">
Name:<input name="name"><br>Email:<input name="email"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
// [Link]
import [Link].*;import [Link].*;import [Link].*;import [Link].*;
public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest r,HttpServletResponse s)throws
ServletException,IOException{
try(PrintWriter out=[Link]()){
[Link]("[Link]");
Connection c=[Link]("jdbc:mysql://localhost:3306/
testdb","root","password");
PreparedStatement p=[Link]("insert into users values(?,?,?)");
[Link](1,[Link]("name"));[Link](2,[Link]("email"));[Link](3,[Link]
arameter("password"));
[Link]([Link]()>0?"Success":"Fail");[Link]();
}catch(Exception e){[Link]();}
}
}
1.16) Servlet program to perform calculation (square & square root) and display results in a
table?
// [Link]
import [Link].*;import [Link].*;import [Link].*;import [Link];
public class CalculationServlet extends HttpServlet {
public void doPost(HttpServletRequest r,HttpServletResponse s)throws
ServletException,IOException{
[Link]("text/html");
PrintWriter out=[Link]();
double num=[Link]([Link]("number"));
double square=num*num;
double sqrt=[Link](num);
DecimalFormat df=new DecimalFormat("#.##");
[Link]("<table border='1'><tr><th>Number</th><th>Square</th><th>Square Root</th></
tr>");
[Link]("<tr><td>"+num+"</td><td>"+[Link](square)+"</td><td>"+[Link](sqrt)+"</
td></tr></table>");
[Link]();
}
}
// HTML Form ([Link])
<form action="CalculationServlet" method="post">
Number: <input type="text" name="number">
<input type="submit" value="Calculate">
</form>
Unit-ll
RequestDispatcher Interface (forward & include, Code-2.3):
2.1) What is the RequestDispatcher Interface? Explain its purpose in a web application?
1. Definition :
i) RequestDispatcher - An interface in [Link] that allows one server-side resource (Servlet,
JSP, HTML) to forward a request or include the output of another resource.
ii) Purpose - Enables internal request routing within the server without informing the client
browser.
iii) Nature - Works on the server side only, unlike sendRedirect(), which involves the client.
2. Role :
i) Forward - Transfers control to another resource without changing the browser URL.
ii) Include - Inserts another resource’s response inside the current output.
iii) Communication - Shares data using [Link]() before forwarding.
iv) Reusability - Encourages modular development by splitting large pages into reusable
components.
v) Performance - Faster than redirection since no new request/response cycle is created.
vi) Encapsulation - Hides internal implementation by forwarding to different resources silently.
vii) Chaining - Allows one servlet to call another, enabling layered processing like validation
processing result display.
3. Example :
i) LoginServlet forwards valid users to DashboardServlet using forward().
ii) A web page includes [Link] and [Link] in multiple pages using include().
2.2) Explain the forward() and include() methods of the RequestDispatcher interface with an
example?
1. Methods of RequestDispatcher :
i) forward(request, response)
a) Transfers the request from one servlet/JSP to another resource on the server.
b) The client is not aware of the transfer — URL remains the same.
c) Used for decision-making scenarios like login validation, grade checking, etc.
d) Once forward() is called, no further output should be written to the response.
ii) include(request, response)
a) Includes the content of another resource within the current response.
b) Control returns to the calling servlet after inclusion.
c) Used to add common components like headers, footers, navigation menus, or ads.
d) Multiple include() calls can be made within a single response.
2. Example :
// In a servlet
RequestDispatcher rd;
if(authenticated) {
rd = [Link]("HomeServlet");
[Link](request, response); // Forward to Home page
} else {
rd = [Link]("[Link]");
[Link](request, response); // Include error message
}
3. Key Differences :
i) forward() ends the current servlet response; include() continues it.
ii) forward() is for redirection within the server; include() is for merging outputs.
iii) forward() is used in decision flow; include() is used in layout building.
2.3) Write a servlet program ([Link]) that accepts a Grade and uses
RequestDispatcher to forward the request to a success or failure page?
//[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class GradeServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException {
String grade = [Link]("grade");
RequestDispatcher rd;
if([Link]("A") || [Link]("B")) {
rd = [Link]("[Link]");
} else {
rd = [Link]("[Link]");
}
[Link](req, res);
}
}
//[Link]
<h2>Congratulations! You Passed.</h2>
//[Link]
<h2>Sorry! Better Luck Next Time.</h2>
Session (Tracking, Life cycle, Rules, Code-2.7):
2.4) What is Session Tracking? Explain its methods and purpose?
1. Definition :
i) Session Tracking - A mechanism used to identify a user across multiple HTTP requests
ii) Working - The server assigns a unique Session ID to each user to maintain continuity
2. Purpose of Session Tracking :
i) User Authentication - Keeps users logged in during navigation
ii) Personalization - Stores user-specific settings like theme or language
iii) Transaction Management - Maintains cart details or form data across pages
iv) Analytics - Helps websites track user activity for improving experience
v) Security Control - Ensures that only authorized users access restricted pages
3. Methods of Session Tracking :
i) Cookies - Stores session ID in client browser as a key-value pair
ii) URL Rewriting - Appends session ID at the end of each URL manually
iii) Hidden Form Fields - Embeds data inside invisible input fields in forms
iv) HttpSession Object - Stores session data on the server side for better security
v) SSL Sessions - Uses secure encrypted connections to maintain session state
4. Example :
i) Online store - when a user adds products to the cart, session tracking ensures items remain
saved while browsing other pages
ii) Login portal - once authenticated, the server identifies the user using a session ID until logout
iii) Banking website - prevents users from accessing account pages after session expiration
2.5) What is a Session? Explain the Lifecycle of an HttpSession?
1. Definition :
i) Session - A server-side mechanism that maintains user data and identity across multiple HTTP
requests
ii) HttpSession - An interface in the Servlet API that helps in creating, accessing, and managing
user sessions
2. Purpose :
i) Maintains - user state across multiple web pages in a single visit
ii) Stores - temporary data such as username, cart details, or preferences
iii) Helps - in authentication, personalization, and user-specific data handling
3. Lifecycle of HttpSession :
i) Creation -
a) Session - created when [Link]() is called for the first time
b) Unique session ID - generated and sent to the client for identification
ii) Access/Usage -
a) Data - stored in the session using setAttribute(name,value)
b) Same data - retrieved using getAttribute(name) during user activity
iii) Timeout or Invalidation -
a) Session expires - after a defined inactive interval (default 30 minutes)
b) It can be manually invalidated using [Link]()
iv) Destruction -
a) All stored data - removed once the session is invalidated or times out
b) User - must re-login or start a new session to continue
4. Example :
i) Login system - when a user logs in, their username and role are stored in HttpSession for
access across pages
ii) E-commerce site - items added to the cart remain stored in session until checkout or logout
2.6) Explain the Rules and General Concepts of Session Management in a Servlet Application?
1. Definition :
i) Session Management - A technique used to track and maintain a user’s interaction with a web
application across multiple requests
ii) Purpose - Ensures that data such as login details or shopping cart information is consistently
available during a user’s active session
2. General Concepts :
i) Session Identification -
a) Each user - is assigned a unique session ID to recognize requests
b) Session ID - is shared between client and server using cookies or URL rewriting
ii) Session Object -
a) HttpSession - represents the session and stores user-specific data
b) Attributes - are added or retrieved using setAttribute() and getAttribute() methods
iii) Timeout Configuration -
a) Session timeout - defines how long a session remains active without user interaction
b) Can be configured - in [Link] using the <session-timeout> tag or programmatically
iv) Session Persistence -
a) Data - remains available across multiple requests until timeout or invalidation
b) Session - helps preserve continuity and user experience in web applications
3. Rules of Session Management :
i) One session - is created per user during interaction with the server
ii) Sensitive data - should not be exposed in URLs for security reasons
iii) Session data - should be minimal to optimize memory usage
iv) Sessions - must be invalidated after logout or inactivity to prevent misuse
4. Example :
i) Banking system - session maintains user authentication and account details until logout
ii) Online exam portal - session keeps track of current questions and remaining time during the
test
2.7) Write a Servlet Program to Create a Session and Display its Details (e.g., Session ID, Creation
Time)?
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class SessionInfoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
HttpSession session = [Link]();
[Link]("<h3>Session Details</h3>");
[Link]("Session ID: " + [Link]() + "<br>");
[Link]("Creation Time: " + new Date([Link]()) + "<br>");
[Link]("Last Accessed Time: " + new Date([Link]()) + "<br>");
}
}
Cookies (Create, Class & Constructor-2.9):
2.8) What is a Cookie? Explain how to Create, Set, Send, and Read Cookies in a Servlet?
1. Definition :
i) Cookie - A small piece of data stored on the client’s browser used to remember information
between requests
ii) Purpose - Helps maintain user state, preferences, and login details across multiple sessions
2. Working of Cookies :
i) The server - sends a cookie to the client using the response object
ii) The client browser - stores the cookie and sends it back to the server with every subsequent
request
3. Cookie Operations in Servlet :
i) Creating and Setting Cookies -
a) Cookie cookie = new Cookie("username", "Adil");
b) [Link](cookie);
ii) Sending Cookies to Client -
a) When response is sent, the cookie is automatically stored in the browser
b) Multiple cookies can be sent using multiple addCookie() calls
iii) Reading Cookies -
a) Cookie[] cookies = [Link]();
b) Loop through cookies and retrieve values using getName() and getValue()
iv) Deleting Cookies -
a) Set the cookie’s max age to 0 using [Link](0);
b) Add the cookie again to remove it from the browser
4. Example :
// Creating and Sending Cookie
Cookie user = new Cookie("username", "Adil");
[Link](user);
// Reading Cookie
Cookie[] cookies = [Link]();
for(Cookie c : cookies){
[Link]([Link]() + " = " + [Link]());
}
5. Example Use Case :
i) Login Page - stores username to greet the user next time they visit the site
ii) E-commerce Website - remembers cart items or preferred settings between sessions
2.9) Describe the Cookie Class with its Constructor and Four Important Methods for
Manipulation?
1. Definition :
i) Cookie Class - A predefined class in the [Link] package used to create and manage
cookies in web applications
ii) Purpose - Helps the server store small pieces of information on the client side to maintain user
sessions or preferences
2. Constructor :
i) Cookie(String name, String value) -
Creates a new cookie with a specified name and value that can be sent to the client browser
3. Important Methods of Cookie Class :
i) setMaxAge(int expiry) -
Sets the lifetime of a cookie in seconds (0 deletes immediately, -1 means it lasts until the browser
closes)
ii) getName() -
Returns the name of the cookie, which acts as a key
iii) getValue() -
Returns the current value of the cookie
iv) setValue(String value) -
Updates the value of an existing cookie stored in the client browser
v) setPath(String path) -
Defines the URL path for which the cookie is valid and accessible
4. Example :
// Creating a Cookie
Cookie user = new Cookie("username", "Adil");
// Setting properties
[Link](3600); // Valid for 1 hour
[Link]("/"); // Available for entire application
// Sending cookie to client
[Link](user);
// Reading cookies from client
Cookie[] cookies = [Link]();
for(Cookie c : cookies){
[Link]([Link]() + " = " + [Link]());
}
File Handling in Servlets (Upload & Download-2.12):
2.10) Explain the Process and Key Considerations for Uploading a File Using a Java Servlet?
1. Definition :
i) File Upload - The process of transferring files from a client’s computer to a server through an
HTTP request
ii) Servlet Role - Handles multipart/form-data requests using the Servlet 3.0 API to receive and
store files on the server
2. Process of File Upload :
i) Client Form - HTML form must include enctype="multipart/form-data" and method="post" to
enable file upload
ii) Servlet Configuration - The servlet must be annotated with @MultipartConfig to define upload
location and file size limits
iii) Reading File Data - The uploaded file is received as a Part object and written to a specific
server directory
iv) Response - After successful upload, the servlet sends confirmation or an error message to the
user
3. Key Considerations :
i) Security - Validate file type and size to prevent malicious uploads
ii) Storage Management - Ensure proper directory permissions and enough disk space
iii) File Size Limit - Set restrictions using @MultipartConfig or server configuration
iv) Error Handling - Provide messages for invalid, large, or missing files
v) User Experience - Inform users about progress, limits, and successful completion
4. Example :
i) Student portal - allows students to upload assignment documents to the server
ii) Job application site - enables applicants to upload resumes or certificates online
2.11) Explain the @MultipartConfig Annotation and its Attributes (e.g., location, maxFileSize)?
1. Definition :
i) @MultipartConfig - An annotation introduced in Servlet 3.0 used to process multipart/form-
data requests for file uploads
ii) Purpose - Enables servlets to receive, handle, and store uploaded files without external libraries
2. Role :
i) Declares - that the servlet can handle file upload operations from HTML forms
ii) Simplifies - file upload configuration by specifying size limits and temporary storage paths
3. Attributes of @MultipartConfig :
i) location -
a) Specifies - the directory on the server where uploaded files will be temporarily stored
b) Example - location = "C:/uploads"
ii) maxFileSize -
a) Defines - the maximum size allowed for a single uploaded file (in bytes)
b) Example - maxFileSize = 1024 * 1024 * 5 (5 MB)
iii) maxRequestSize -
a) Specifies - the total size limit for the complete request including multiple files and form data
b) Prevents - server overload by restricting total upload size
iv) fileSizeThreshold -
a) Determines - the size threshold after which files are written to disk instead of memory
b) Smaller files - are stored temporarily in memory
4. Example :
i) In a resume upload form, @MultipartConfig ensures users can upload files only under 5 MB size
ii) It prevents errors and enhances server performance by controlling upload limits
2.12) Write a Servlet Program to Handle a File Download Request?
1. Definition :
i) File Download - A process that allows users to retrieve files stored on the server to their local
system
ii) Servlet Role - Handles download requests by reading files from the server and sending them as
response data to the client
2. Working of File Download :
i) Request Handling - The user clicks a download link or button that sends a request to the servlet
ii) File Retrieval - The servlet locates the requested file from the server directory
iii) Response Setup - The servlet sets the MIME type and Content-Disposition header to trigger the
browser’s download dialog
iv) Data Transfer - The file’s binary data is sent through the response output stream to the client
3. Key Steps :
i) Locate File - Find the path of the file on the server using ServletContext or predefined directory
ii) Set Response Headers -
a) [Link]("application/octet-stream") to specify binary data
b) [Link]("Content-Disposition", "attachment; filename=[Link]") to prompt
download
iii) Stream File - Use InputStream to read file and OutputStream to send it to the client
iv) Close Streams - Ensure both input and output streams are closed after download completion
4. Example :
i) A student portal - allows students to download assignment guidelines or notes uploaded by
teachers
ii) A company intranet - lets employees download policy documents or reports stored on the
server
Non-Blocking I/O(ReadListener, WriteListener, onDataRead()-2.16):
2.13) What is Non-Blocking I/O and How Does it Work in the Context of Servlets?
1. Definition :
i) Non-Blocking I/O - A feature introduced in Servlet 3.1 that allows servlets to handle multiple I/O
operations simultaneously without waiting for one to finish
ii) Purpose - Improves scalability and performance by freeing threads while waiting for input/
output operations like reading or writing data
2. Working of Non-Blocking I/O :
i) Traditional I/O - Servlet thread waits (blocks) until input/output is complete before continuing
to process requests
ii) Non-Blocking I/O - Servlet thread registers a listener and is released, allowing the container to
notify it when data is available or writable
iii) Event-Based Model - Uses listener interfaces like ReadListener and WriteListener to handle
asynchronous read and write events
3. Key Concepts :
i) Asynchronous Processing - Servlet threads are not tied to one request and can serve multiple
clients concurrently
ii) ReadListener - Triggered when input data is available to read from the client
iii) WriteListener - Triggered when the servlet can send output data to the client
iv) Efficiency - Reduces thread blocking and resource usage, making it ideal for real-time
applications
4. Example :
i) Chat applications - handle multiple user messages simultaneously without blocking threads
ii) File upload/download services - can serve many users concurrently using non-blocking I/O to
improve speed and efficiency
2.14) Explain the ReadListener and WriteListener Interfaces Used in Non-Blocking I/O?
1. Definition :
i) ReadListener and WriteListener - Interfaces introduced in Servlet 3.1 to support asynchronous
and non-blocking input/output processing
ii) Purpose - Allow servlets to perform read and write operations without blocking the main
thread, improving scalability and performance
2. ReadListener Interface :
i) Role - Handles asynchronous reading of data from the client input stream
ii) Methods -
a) onDataAvailable() - Invoked when data is available to read from the client
b) onAllDataRead() - Called when all data has been read completely
c) onError(Throwable t) - Triggered if an error occurs while reading input
iii) Benefit - Enables the servlet to read data in small chunks without waiting for the entire request
to finish
3. WriteListener Interface :
i) Role - Handles asynchronous writing of data to the client output stream
ii) Methods -
a) onWritePossible() - Called when the servlet can write data to the client without blocking
b) onError(Throwable t) - Invoked when an error occurs during output writing
iii) Benefit - Allows efficient, non-blocking sending of large responses such as files or streamed
data
4. Example :
i) ReadListener - used when receiving large JSON data from a client without blocking
ii) WriteListener - used when sending live data updates or large reports to multiple users
2.15) Write a Program to Implement a ReadListener?
1. Definition :
i) ReadListener - An interface in Servlet 3.1 that supports asynchronous, non-blocking reading of
input data from the client
ii) Purpose - Allows servlets to handle data as it becomes available without blocking threads,
improving scalability and response time
2. Role of ReadListener :
i) Enables asynchronous reading - the servlet is notified when new input data is available
ii) Prevents blocking - frees up server threads while waiting for I/O operations
iii) Commonly used - in applications requiring large or continuous data input like chat servers or
streaming systems
3. Key Methods of ReadListener :
i) onDataAvailable() - Called when data can be read from the client input stream
ii) onAllDataRead() - Invoked when all input data has been completely read
iii) onError(Throwable t) - Triggered when an error occurs during reading
4. Working Steps :
i) Obtain - AsyncContext and ServletInputStream from the request object
ii) Set - the ReadListener to handle incoming data asynchronously
iii) Implement - the three ReadListener methods to manage read operations and errors
iv) Process - the incoming data when onDataAvailable() is triggered
5. Example :
i) A chat application - uses ReadListener to read live user messages asynchronously as they arrive
ii) A file upload service - reads data chunks asynchronously from large client uploads without
blocking the server
2.16) Explain the onDataAvailable() and onAllDataRead() Methods of the ReadListener Interface
with a Code Snippet?
1. Definition :
i) ReadListener - An interface introduced in Servlet 3.1 to support non-blocking I/O for reading
client input asynchronously.
ii) Purpose - Enables servlets to process incoming data without blocking threads, allowing better
scalability and real-time data handling.
2. onDataAvailable() Method :
i) Description - Called when input data is available to be read from the client.
ii) Working - The servlet reads available data chunks using [Link]() and
processes them without waiting for the entire request to complete.
iii) Example Use - Ideal for reading continuous data streams such as file uploads or live sensor
data.
3. onAllDataRead() Method :
i) Description - Triggered once all input data has been completely read.
ii) Working - Indicates that no more data is available, and post-processing (e.g., saving data or
sending response) can begin.
iii) Example Use - Used to close streams or send acknowledgment after data upload completion.
4. Example Code Snippet :
ServletInputStream input = [Link]();
[Link](new ReadListener() {
public void onDataAvailable() throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ([Link]() && (bytesRead = [Link](buffer)) != -1) {
// Process input data chunk
}
}
public void onAllDataRead() throws IOException {
// All data has been read, send response or perform post-processing
}
public void onError(Throwable t) {
[Link]();
}
});
Unit-lll
JSP Fundamentals & Lifecycle(DB Servlet and JSP-3.3):
3.1) What is the Use of Java Server Pages (JSP)? Explain the Reasons to Use Them?
1. Definition :
i) JSP (Java Server Pages) - A server-side technology used to create dynamic and platform-
independent web pages using Java.
ii) It allows embedding Java code directly into HTML using special JSP tags, simplifying the
development of interactive web applications.
2. Purpose of JSP :
i) Simplifies - dynamic web page development by mixing Java with HTML.
ii) Reduces - complexity compared to servlets by minimizing Java code in presentation logic.
iii) Enables - faster web application development with reusable components.
3. Reasons to Use JSP :
i) Separation of Concerns - Business logic is handled by servlets or beans, while JSP manages
presentation.
ii) Easy Maintenance - Developers can update the UI without modifying backend logic.
iii) Reusability - JSP supports custom tags, JavaBeans, and reusable components.
iv) Integration - Works seamlessly with Java EE technologies such as Servlets, JDBC, and EJB.
v) Implicit Objects - JSP provides predefined objects (request, response, session, etc.) for easy
access to web components.
vi) Automatic Compilation - JSP pages are automatically compiled into servlets by the container
for efficient execution.
vii) Extensibility - JSP can include reusable fragments like headers and footers using directives or
include actions.
4. Example :
i) Login page - A JSP file displays the form and uses backend Java code to validate credentials
dynamically.
ii) Product page - Fetches and displays product data from a database using JSP and JDBC.
3.2) Distinguish Between a Servlet and a JSP?
1. Definition :
i) Servlet - A Java program that runs on the server, handles client requests, processes business
logic, and generates dynamic responses.
ii) JSP (Java Server Pages) - A server-side scripting technology used mainly for presentation,
allowing HTML and Java code to be combined for dynamic content generation.
2. Difference Between Servlet and JSP :
i) Nature -
a) Servlet - Code-centric, focuses on logic and request handling.
b) JSP - Page-centric, focuses on presentation and content display.
ii) Syntax -
a) Servlet - Written entirely in Java.
b) JSP - Mostly HTML with embedded Java code using tags.
iii) Compilation -
a) Servlet - Must be manually compiled and deployed.
b) JSP - Automatically compiled into a servlet by the container.
iv) Maintenance -
a) Servlet - Harder to maintain because HTML is mixed with Java code.
b) JSP - Easier to maintain since Java logic is minimal and mostly separated from HTML.
v) Use Case -
a) Servlet - Best for processing requests, managing data, and business logic.
b) JSP - Best for presenting data and designing user interfaces.
vi) Lifecycle -
a) Servlet - Created, initialized, and managed directly by the container.
b) JSP - First translated into a servlet, then follows the servlet lifecycle.
vii) Code Reusability -
a) Servlet - Can call other classes or components for reuse.
b) JSP - Can include reusable fragments using directives or tag libraries.
3. Example :
i) Servlet - Handles login verification by connecting to the database and validating user
credentials.
ii) JSP - Displays the login form and shows success or failure messages to the user.
3.3) Explain the Life Cycle of a JSP Page with a Diagram?
1. Definition :
i) JSP (Java Server Pages) - A server-side technology that simplifies the creation of dynamic web
content by embedding Java code into HTML.
ii) JSP Life Cycle - Refers to the process followed by the JSP container from the creation of a JSP
page to its destruction.
2. JSP Life Cycle Phases :
i) Translation Phase -
a) The JSP file is translated into a Java servlet by the container.
b) The translated servlet contains equivalent Java code for embedded JSP elements.
ii) Compilation Phase -
a) The generated servlet file (.java) is compiled into a .class file.
b) Any syntax or tag errors are checked during this phase.
iii) Initialization Phase (jspInit() method) -
a) Called once when the JSP is loaded into memory.
b) Used for initializing resources such as database connections or configuration settings.
iv) Request Processing Phase (_jspService() method) -
a) Executed each time a request is received from a client.
b) Handles request processing, executes embedded Java code, and generates dynamic
responses.
v) Destruction Phase (jspDestroy() method) -
a) Called when the JSP is unloaded from memory.
b) Used for cleanup activities like releasing resources or closing connections.
3. Diagram :
Client Request
!
JSP Page (.jsp)
! (Translation)
JSP Converted to Servlet (.java)
! (Compilation)
Servlet Compiled to Bytecode (.class)
!
jspInit() _jspService() jspDestroy()
!
Response Sent to Client
JSP Scripting Elements & Directives(Types, Attribute-3.6):
3.4) Explain the Different Types of JSP Tags (Scripting Elements) with Examples?
1. Definition :
i) JSP Scripting Elements - These are special tags used to embed Java code within an HTML page
to add dynamic behavior.
ii) Purpose - Allows developers to insert, declare, and control Java logic inside JSP pages.
2. Types of JSP Scripting Elements :
i) Declaration Tag (<%! ... %>) -
a) Used - To declare variables and methods that are available to the entire JSP page.
b) Syntax - <%! int count = 0; String greet(){ return "Hello"; } %>
c) Example - Declaring a counter variable used across multiple requests.
ii) Scriptlet Tag (<% ... %>) -
a) Used - To write Java code that is executed each time the page is requested.
b) Syntax - <% int x = 5; [Link]("Value: " + x); %>
c) Example - Displaying dynamic data such as user details or database output.
iii) Expression Tag (<%= ... %>) -
a) Used - To output values directly into the response without using [Link]().
b) Syntax - <%= "Welcome, " + username %>
c) Example - Displaying a username dynamically on a welcome page.
iv) Comment Tag (<%-- ... --%>) -
a) Used - To add comments in JSP that are not visible in the client’s browser or final HTML.
b) Syntax - <%-- This is a JSP comment --%>
c) Example - Used for internal developer notes in JSP pages.
3. Example :
<html>
<body>
<%! int visitCount = 0; %>
<% visitCount++; %>
<h2>Visitor Number: <%= visitCount %></h2>
<%-- This counter increases with each page load --%>
</body>
</html>
3.5) What are Directives in JSP? Explain the Different Types?
1. Definition :
i) JSP Directives - Instructions that provide global-level information to the JSP container about
page structure and behavior during translation.
ii) Purpose - Used to control how the JSP page is processed, including importing packages,
defining error pages, and including other resources.
2. Types of JSP Directives :
i) Page Directive -
a) Used - To define page-level settings like importing classes, managing error handling, and
defining content type.
b) Syntax - <%@ page attribute="value" %>
c) Common Attributes -
•import – Imports Java packages (e.g., import="[Link].*")
•contentType – Defines response type (e.g., contentType="text/html")
•errorPage – Redirects to a specific page on error (e.g., errorPage="[Link]")
•session – Enables or disables session (session="true" or "false")
ii) Include Directive -
a) Used - To include static files (HTML, JSP fragments) into the current page during translation.
b) Syntax - <%@ include file="[Link]" %>
c) Example - Including header or footer templates across multiple pages for reusability.
iii) Taglib Directive -
a) Used - To define and use custom tag libraries in JSP pages.
b) Syntax - <%@ taglib uri="[Link] prefix="c" %>
c) Example - Used with JSTL (JavaServer Pages Standard Tag Library) for looping, conditions,
and expressions.
3. Example :
<%@ page import="[Link].*" contentType="text/html" %>
<%@ include file="[Link]" %>
<%@ taglib uri="[Link] prefix="c" %>
<html>
<body>
<h3>Today's Date: <%= new Date() %></h3>
</body>
</html>
3.6) Explain the Page Directive in Detail with All Its Attributes?
1. Definition :
i) Page Directive - A JSP directive that defines global settings for a JSP page such as importing
classes, content type, session management, and error handling.
ii) Syntax - <%@ page attribute="value" %>
iii) Purpose - Informs the JSP container how to process and handle the page during translation
and execution.
2. Common Attributes of Page Directive :
i) import -
a) Used - To import Java packages or classes for use within the JSP page.
b) Example - <%@ page import="[Link].*, [Link].*" %>
ii) contentType -
a) Used - To define the MIME type and character encoding of the response.
b) Example - <%@ page contentType="text/html;charset=UTF-8" %>
iii) session -
a) Used - To enable or disable session tracking for a JSP page.
b) Example - <%@ page session="true" %> (default value is true)
iv) errorPage -
a) Used - To specify the JSP page that will handle exceptions thrown by the current page.
b) Example - <%@ page errorPage="[Link]" %>
v) isErrorPage -
a) Used - To declare whether the current page is an error-handling page.
b) Example - <%@ page isErrorPage="true" %>
vi) language -
a) Used - To define the scripting language used in the JSP (usually Java).
b) Example - <%@ page language="java" %>
vii) extends -
a) Used - To specify a superclass that the generated servlet will extend.
b) Example - <%@ page extends="[Link]" %>
viii) buffer -
a) Used - To specify the buffer size for the response output.
b) Example - <%@ page buffer="8kb" %>
ix) autoFlush -
a) Used - To control whether the buffer is automatically flushed when full.
b) Example - <%@ page autoFlush="true" %>
x) info -
a) Used - To provide descriptive information about the JSP page.
b) Example - <%@ page info="This page displays user information" %>
xi) isELIgnored -
a) Used - To specify whether Expression Language (EL) is ignored in the JSP.
b) Example - <%@ page isELIgnored="false" %>
JSP Actions & Practical Application(forward request, Bean, Plugin-3.10):
3.7) How Do You Forward a Request and Pass Parameters to Another Page in JSP?
1. Definition :
i) Request Forwarding - The process of transferring a client request from one JSP or servlet to
another resource (like another JSP or HTML page) on the same server.
ii) Purpose - Helps in reusing resources, separating logic from presentation, and simplifying web
page navigation.
2. Ways to Forward a Request in JSP :
i) Using <jsp:forward> Action Tag -
a) Used - To forward a request to another page on the server.
b) Syntax - <jsp:forward page="[Link]" />
c) Example - <jsp:forward page="[Link]" />
ii) Using RequestDispatcher Interface -
a) Used - In servlets or JSPs for conditional forwarding.
b) Syntax -
<%
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
%>
3. Passing Parameters During Forwarding :
i) Using <jsp:param> Tag -
a) Allows passing parameters to the forwarded page.
b) Syntax -
<jsp:forward page="[Link]">
<jsp:param name="username" value="John" />
<jsp:param name="role" value="Admin" />
</jsp:forward>
c) The receiving JSP can access parameters using:
<%= [Link]("username") %>
ii) Using Request Attributes -
a) Data is set before forwarding using [Link]().
b) Syntax -
<%
[Link]("user", "John");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
%>
c) The forwarded page retrieves data using:
<%= [Link]("user") %>
3.8) Explain the <jsp:useBean> Action Tag with Its Attributes and Usage, Providing a Suitable
Example?
1. Definition :
i) <jsp:useBean> - A JSP action tag used to create or access a JavaBean object in a JSP page.
ii) Purpose - Helps separate business logic from presentation by using reusable Java
components.
2. Syntax :
<jsp:useBean id="beanName" class="[Link]" scope="scopeType" />
3. Attributes :
i) id - Name to access the bean in the JSP page.
ii) class - Fully qualified JavaBean class name.
iii) scope - Defines bean lifespan (page, request, session, or application).
4. Related Tags :
i) <jsp:setProperty> - Sets property values for a bean.
Example - <jsp:setProperty name="user" property="username" value="Adil" />
ii) <jsp:getProperty> - Retrieves and displays bean properties.
Example - <jsp:getProperty name="user" property="username" />
5. Example :
//[Link]
package [Link];
public class UserBean {
private String name;
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
}
//[Link]
<jsp:useBean id="user" class="[Link]" scope="session" />
<jsp:setProperty name="user" property="name" value="Adil" />
Welcome, <jsp:getProperty name="user" property="name" />!
3.9) Write a Short Note on the <jsp:plugin> Action?
1. Definition :
i) <jsp:plugin> - A JSP action tag used to include and execute Java applets or JavaBeans in a web
page.
ii) Purpose - Ensures that the client browser can run Java components by automatically
generating the appropriate HTML <object> or <embed> tags.
2. Syntax :
<jsp:plugin type="applet" code="[Link]" width="width" height="height"></jsp:plugin>
3. Attributes :
i) type - Specifies the component type (applet or bean).
ii) code - Refers to the class file of the applet or bean.
iii) codebase - Path or URL where the class file is located.
iv) width / height - Defines the display area for the component.
v) archive - Specifies a JAR file that contains required classes.
vi) name - Assigns an identifier to the applet or bean instance.
4. Subtags :
i) <jsp:params> - Used to pass parameters to the applet or bean.
ii) <jsp:fallback> - Displays alternative content if the plugin is not supported by the browser.
5. Example :
<jsp:plugin type="applet" code="[Link]" width="300" height="200">
<jsp:params>
<jsp:param name="version" value="1.0" />
</jsp:params>
<jsp:fallback>
Your browser does not support Java applets.
</jsp:fallback>
</jsp:plugin>
3.10) Develop a Simple JSP Application to Accept Various Input Values from an HTML Page and
Display Them on the Next Page?
//[Link]
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<h2>Enter Your Details</h2>
<form action="[Link]" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Age: <input type="number" name="age"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
Hobbies:
<input type="checkbox" name="hobby" value="Reading"> Reading
<input type="checkbox" name="hobby" value="Music"> Music<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
//[Link]
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Details</title>
</head>
<body>
<h2>User Information</h2>
<table border="1" cellpadding="5">
<tr><td>Name</td><td><%= [Link]("name") %></td></tr>
<tr><td>Email</td><td><%= [Link]("email") %></td></tr>
<tr><td>Age</td><td><%= [Link]("age") %></td></tr>
<tr><td>Gender</td><td><%= [Link]("gender") %></td></tr>
<tr><td>Hobbies</td>
<td>
<%
String[] hobbies = [Link]("hobby");
if (hobbies != null) {
for (String h : hobbies) [Link](h + " ");
} else [Link]("None");
%>
</td>
</tr>
</table>
</body>
</html>
JSP Implicit Objects & Scopes(page, request, session, application-3.13):
3.11) List the JSP Implicit Objects and Explain Any Four in Detail?
1. Definition :
i) Implicit Objects - Predefined objects available in JSP pages without explicit declaration.
ii) Purpose - Simplify interaction between server, client, and application by providing direct access
to request, response, session, and context data.
2. List of JSP Implicit Objects :
i) request
ii) response
iii) out
iv) session
v) application
vi) config
vii) page
viii) pageContext
ix) exception
3. Explanation of Four Important Implicit Objects :
i) request -
a) Represents - Client’s request sent to the server.
b) Provides - Access to form data, headers, and attributes.
c) Methods - getParameter(), getAttribute(), getRequestDispatcher()
d) Example - <%= [Link]("username") %>
ii) response -
a) Represents - The server’s response to the client.
b) Used - To redirect pages or set content types.
c) Methods - sendRedirect(), setContentType()
d) Example - <% [Link]("[Link]"); %>
iii) session -
a) Represents - User session for storing temporary data across multiple pages.
b) Used - To store attributes like user info or preferences.
c) Methods - setAttribute(), getAttribute(), invalidate()
d) Example - <% [Link]("user","Adil"); %>
iv) out -
a) Used - To send output to the client browser.
b) Represents - JspWriter object.
c) Methods - print(), println(), flush()
d) Example - <% [Link]("Welcome to JSP"); %>
4. Example :
<%
String name = [Link]("name");
[Link]("user", name);
[Link]("Hello, " + name);
%>
3.12) Explain the Methods of the Request Implicit Object in JSP?
1. Definition :
i) The request object in JSP is an instance of HttpServletRequest used to get information from
the client and pass data between resources.
ii) Purpose - Provides access to form parameters, attributes, headers, and session data for
processing user input.
2. Common Methods of the Request Object :
i) getParameter(String name) -
a) Retrieves - The value of a form field sent from the client.
b) Example - <%= [Link]("username") %>
ii) getParameterValues(String name) -
a) Returns - Multiple values of a parameter (e.g., checkboxes).
b) Example -
String[] hobbies = [Link]("hobby");
for(String h : hobbies) [Link](h + " ");
iii) getAttribute(String name) -
a) Retrieves - Attribute stored in the request scope.
b) Example - <%= [Link]("user") %>
iv) setAttribute(String name, Object value) -
a) Stores - Data as an attribute to share between servlets or JSPs.
b) Example - <% [Link]("id", 101); %>
v) getMethod() -
a) Returns - The HTTP request method (GET or POST).
b) Example - <%= [Link]() %>
3. Example :
<%
String name = [Link]("name");
[Link]("greet", "Hello " + name);
[Link]([Link]("greet"));
%>
3.13) Explain the Various Scopes of JSP Objects (page, request, session, application)?
1. Definition :
i) Scope in JSP - Defines the lifespan and accessibility of variables or objects created in a JSP
page.
ii) Purpose - Determines how long data remains available and which components can access it
during execution.
2. Types of JSP Scopes :
i) page Scope -
a) Availability - Accessible only within the current JSP page.
b) Lifetime - Exists until the page execution completes.
c) Default scope for JSP objects.
d) Example -
<jsp:useBean id="user" class="[Link]" scope="page" />
ii) request Scope -
a) Availability - Accessible across multiple resources (JSPs or Servlets) during a single client
request.
b) Lifetime - Exists until the server sends a response to the client.
c) Example -
[Link]("name", "Adil");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
iii) session Scope -
a) Availability - Accessible across multiple requests from the same user.
b) Lifetime - Exists until the user logs out or the session expires.
c) Example -
[Link]("user", "Adil");
String name = (String) [Link]("user");
iv) application Scope -
a) Availability - Shared across the entire web application for all users and sessions.
b) Lifetime - Exists until the server is shut down or the application is undeployed.
c) Example -
[Link]("visits", 100);
Expression Language (EL) & JSTL(Operators, Library-3.16):
3.14) What is Expression Language (EL)? Explain Its Operators and Concepts Like Immediate vs.
Deferred EL?
1. Definition :
i) Expression Language (EL) - A feature in JSP used to simplify access to application data stored
in JavaBeans, request, session, and application scopes.
ii) Purpose - Reduces Java code in JSP by replacing scriptlets (<% %>) with concise expressions
like ${expression}.
2. Syntax :
i) Basic Format - ${expression}
ii) Example - ${[Link]} retrieves the “name” property of the “user” object.
3. Types of EL :
i) Immediate EL (${}) -
a) Evaluated immediately when the JSP page is executed.
b) Used - In standard JSP pages for direct expression evaluation.
c) Example - ${2 + 3} Output: 5
ii) Deferred EL (#{}) -
a) Evaluated later, often used in JSF (JavaServer Faces) and tag files.
b) Used - When the expression must be processed at a later phase.
c) Example - #{[Link]} (evaluated when JSF component is rendered).
4. EL Operators :
i) Arithmetic - +, -, *, /, %
Example - ${10 + 5} 15
ii) Relational - ==, !=, <, >, <=, >=
Example - ${age > 18} true
iii) Logical - &&, ||, !
Example - ${loggedIn && admin}
iv) Empty Operator - Checks if a value is null or empty.
Example - ${empty [Link]}
v) Conditional (?:) - Ternary operator for decision-making.
Example - ${age >= 18 ? 'Adult' : 'Minor'}
vi) Dot & Bracket Notation - Access properties or map keys.
Example - ${[Link]} or ${user["email"]}
3.15) What is JSTL? Explain Its Advantages and How It Fixes the Shortcomings of JSP Scriptlet
Tags?
1. Definition :
i) JSTL (JavaServer Pages Standard Tag Library) - A collection of custom tags that simplify
common tasks like looping, condition checking, formatting, and database access in JSP.
ii) Purpose - Reduces the use of Java scriptlets (<% %>) and promotes clean, maintainable, and
reusable JSP code.
2. Tag Library Declaration :
<%@ taglib uri="[Link] prefix="c" %>
3. Advantages of JSTL :
i) Readability - Removes Java code from JSP, making pages easier to understand.
ii) Reusability - Common tasks like looping, condition checking, and formatting are standardized.
iii) Maintainability - Easier to maintain due to clear separation of logic and presentation.
iv) Portability - JSTL is platform-independent and works with any Java EE-compliant server.
v) Security - Eliminates the need for scriptlets, reducing potential coding errors.
4. JSTL Tag Libraries :
i) Core Tags (c) - Provides control flow, variable manipulation, and URL management.
Example - <c:if>, <c:forEach>, <c:choose>
ii) Formatting Tags (fmt) - Used for date, number, and message formatting.
iii) SQL Tags (sql) - For database operations like query and update (used rarely for small apps).
iv) XML Tags (x) - For parsing and transforming XML data.
v) Functions (fn) - Provides string and collection functions.
3.16) Explain the JSTL Core Tag Library with Examples of Different Core Tags?
1. Definition :
i) JSTL Core Tag Library - A collection of standard tags used for controlling flow, iterating data,
managing variables, and performing conditional logic in JSP.
ii) Purpose - Simplifies JSP code by replacing Java scriptlets with XML-style tags for cleaner and
more maintainable pages.
2. Tag Library Declaration :
<%@ taglib uri="[Link] prefix="c" %>
3. Common JSTL Core Tags and Their Usage :
i) <c:out> –
a) Used - To display dynamic data (like [Link]()).
b) Example - <c:out value="${user}" />
ii) <c:set> –
a) Used - To assign a value to a variable.
b) Example - <c:set var="name" value="Adil" />
iii) <c:remove> –
a) Used - To remove a variable from scope.
b) Example - <c:remove var="name" />
iv) <c:if> –
a) Used - To execute code conditionally.
b) Example - <c:if test="${age >= 18}">Eligible</c:if>
v) <c:forEach> –
a) Used - To iterate over a collection or list.
b) Example - <c:forEach var="x" items="${list}">${x}</c:forEach>
vi) <c:forTokens> –
a) Used - To split and loop through tokens.
b) Example - <c:forTokens items="Red,Blue" delims="," var="c">${c}</c:forTokens>
vii) <c:import> –
a) Used - To include content from another file.
b) Example - <c:import url="[Link]" />
viii) <c:redirect> –
a) Used - To redirect to another page.
b) Example - <c:redirect url="[Link]" />
Unit-lV
EJB( Architecture, Benefits, Advantages, Container, Types, Remote and Local Interfaces, Data
source-4.6):
4.1) What is an Enterprise JavaBean (EJB)? Explain its Architecture?
1. Definition :
i) EJB (Enterprise JavaBean) - A server-side component of Java EE used to build scalable,
distributed, and transactional enterprise applications.
ii) Purpose - Simplifies the development of large-scale business applications by handling system-
level services like transactions, security, and concurrency automatically.
2. Features of EJB :
i) Transaction Management - Supports automatic transaction handling.
ii) Security - Provides declarative and programmatic security.
iii) Remote Access - Allows distributed applications to communicate across networks.
iv) Persistence - Handles database operations through entity beans or JPA.
v) Scalability - Supports load balancing and concurrent access.
vi) Container-Managed - The EJB container handles lifecycle, transactions, and resource
management.
3. EJB Architecture :
i) Client Layer - Invokes business methods of EJB components through remote/local interfaces.
ii) EJB Container - Manages EJB components, handles lifecycle, transactions, and security.
iii) Enterprise Beans - Core business logic units (Session, Message-Driven, Entity).
iv) Java Naming and Directory Interface (JNDI) - Used for locating and accessing EJB
components.
v) Database/Resource Layer - Interacts with databases and external resources using JDBC or
JPA.
4. Example :
i) In an online banking system, an EJB can handle operations like fund transfer, balance inquiry,
and transaction management securely and efficiently.
4.2) Explain the Benefits and Advantages of using EJB?
1. Definition :
i) EJB (Enterprise JavaBean) - A server-side component used to develop distributed,
transactional, and secure enterprise-level applications.
ii) Purpose - Simplifies business logic development by letting the container handle system-level
services like transactions, security, and resource management.
2. Benefits and Advantages :
i) Simplified Development -
a) Developers - focus on business logic.
b) Container - manages lifecycle, security, and transactions automatically.
ii) Transaction Management -
a) Supports - declarative and programmatic transactions.
b) Ensures - data integrity and consistency.
iii) Security -
a) Provides - built-in authentication and authorization.
b) Reduces - manual security handling through container management.
iv) Scalability -
a) Handles - multiple clients using multithreading.
b) Container - provides load balancing and resource pooling.
v) Reusability -
a) Components - reused across multiple applications.
b) Improves - maintainability and reduces redundancy.
vi) Interoperability -
a) Supports - RMI and web services.
b) Enables - distributed platform communication.
vii) Integration -
a) Works - with JDBC, JMS, and JNDI.
b) Connects - easily to databases and external systems.
3. Example :
i) In a banking application, EJBs manage user transactions, security checks, and database
updates without manual coding for transaction or connection management.
4.3) Explain the Role of the Enterprise Bean Container?
1. Definition :
i) EJB Container - A runtime environment that manages the execution of Enterprise JavaBeans
(EJB) within an application server.
ii) Purpose - Provides system-level services such as transaction management, security, lifecycle,
and concurrency control.
2. Role of EJB Container :
i) Lifecycle Management -
a) Creates - beans and manages their activation and destruction.
b) Ensures - efficient resource utilization and automatic cleanup.
ii) Transaction Management -
a) Handles - distributed transactions automatically.
b) Ensures - data integrity and rollback in case of failure.
iii) Security Management -
a) Provides - declarative and programmatic security.
b) Manages - user authentication and authorization transparently.
iv) Resource Management -
a) Manages - connections to databases, JMS, and other resources.
b) Handles - pooling and sharing of system resources efficiently.
v) Interception and Communication -
a) Intercepts - client requests and forwards them to appropriate beans.
b) Manages - remote and local invocations seamlessly.
vi) Concurrency Control -
a) Ensures - thread safety for multiple client requests.
b) Prevents - conflicts during simultaneous access.
3. Example :
i) In a banking system, the EJB container manages fund transfer beans, ensuring secure
transactions and automatic rollback during errors.
4.4) What are the Different Types of Enterprise Beans?
1. Definition :
i) Enterprise Beans - Server-side components in the EJB framework that encapsulate business
logic and provide reusable enterprise functionality.
ii) Purpose - Simplifies the creation of distributed, secure, and transactional applications by
separating business logic from infrastructure concerns.
2. Types of Enterprise Beans :
i) Session Beans -
a) Manage - business logic and interact with clients directly.
b) Types - Stateless (no client state), Stateful (maintains client state), and Singleton (one
instance shared by all clients).
c) Example - A shopping cart or login session handler.
ii) Message-Driven Beans (MDB) -
a) Handle - asynchronous message processing using Java Message Service (JMS).
b) Used - for background tasks such as notifications, email sending, or order processing.
c) Example - A system that processes orders received via a message queue.
iii) Entity Beans (Deprecated) -
a) Represent - persistent data stored in a database.
b) Managed - by the container to handle CRUD operations automatically.
c) Replaced - by Java Persistence API (JPA) for improved data handling.
3. Example :
i) Session Bean - Handles payment processing in an online store.
ii) Message-Driven Bean - Processes order confirmations in the background.
4.5) Write a Short Note on Remote and Local Interfaces in EJB?
1. Definition :
i) EJB Interfaces - Define how clients interact with enterprise beans.
ii) Types - Remote interface and Local interface based on client location.
2. Remote Interface :
i) Allows - access to EJBs from remote JVMs.
ii) Uses - RMI (Remote Method Invocation) for communication.
iii) Suitable - for distributed applications with remote clients.
iv) Example - @Remote annotation defines remote access in EJB.
3. Local Interface :
i) Allows - access within the same JVM or application module.
ii) Provides - faster communication without network overhead.
iii) Suitable - for tightly coupled components within the same server.
iv) Example - @Local annotation defines local access in EJB.
4. Difference :
i) Remote - Higher latency, suitable for distributed systems.
ii) Local - Faster, suitable for single-server deployments.
5. Example :
i) Remote Interface - Used in multi-tier web applications where web and business logic layers are
on different servers.
ii) Local Interface - Used in monolithic enterprise systems where all components run on the same
server.
4.6) Write a Note on DataSource Resource Definition in Java EE?
1. Definition :
i) DataSource - A Java EE resource that provides a standard way for applications to connect to
databases.
ii) Purpose - Simplifies database connectivity by allowing connection pooling, transaction
management, and resource configuration managed by the server.
2. Role of DataSource :
i) Provides - a standardized API for obtaining database connections.
ii) Eliminates - the need to hard-code database details in applications.
iii) Improves - performance using connection pooling and caching.
iv) Ensures - secure access with centralized credential management.
3. Configuration :
i) Defined - in the deployment descriptor ([Link]) or annotated in code using
@DataSourceDefinition.
ii) Server - manages and provides the DataSource to applications through JNDI lookup.
4. Example :
@DataSourceDefinition(
name = "java:app/jdbc/myDB",
className = "[Link]",
user = "root",
password = "admin",
databaseName = "studentdb",
serverName = "localhost",
portNumber = 3306
)
public class DBConfig { }
Session Beans(Types, Lifecycle, code-4.9):
4.7) Write a Note on the Different Types of Session Beans (Stateless, Stateful, Singleton)?
1. Definition :
i) Session Beans - Enterprise Beans that handle business logic and client interaction in an EJB
application.
ii) Purpose - Manage user-related operations like transactions, requests, and services for
enterprise applications.
2. Types of Session Beans :
i) Stateless Session Bean -
a) Definition - Does not maintain client state between method calls.
b) Use - Best for independent, repeatable operations like calculations or validations.
c) Advantage - High performance and scalability.
d) Example - Currency conversion or authentication check.
ii) Stateful Session Bean -
a) Definition - Maintains conversational state for a specific client across multiple requests.
b) Use - Suitable for user sessions or workflows requiring data persistence.
c) Advantage - Ideal for shopping carts, online bookings, or login sessions.
d) Example - E-commerce cart tracking user’s selected items.
iii) Singleton Session Bean -
a) Definition - A single instance shared by all clients within an application.
b) Use - Best for global configurations, logging, caching, or resource management.
c) Advantage - Reduces memory usage and ensures centralized data handling.
d) Example - Application-wide configuration manager or caching service.
3. Difference Summary :
i) Stateless - No client state, highly scalable.
ii) Stateful - Maintains client-specific data.
iii) Singleton - Shared single instance across application.
4.8) Explain the Lifecycle of a Stateful Session Bean?
1. Definition :
i) Stateful Session Bean - A session bean that maintains the conversational state of a specific
client across multiple requests.
ii) Purpose - Used when client data must be preserved between method calls such as in shopping,
booking, or banking transactions.
2. Lifecycle of a Stateful Session Bean :
i) Does Not Exist -
a) State - Bean instance does not exist before creation.
b) Action - Container creates a new instance when a client requests it.
ii) Instantiated / Created -
a) State - Bean instance is created using the default constructor.
b) Action - Container performs dependency injection and sets up environment resources.
iii) Initialized -
a) State - Bean is prepared for client interaction.
b) Action - The @PostConstruct method executes initialization logic (e.g., variable setup,
connection creation).
iv) Ready / Method-Ready State -
a) State - Bean is active and associated with a specific client.
b) Action - Executes business methods while maintaining client-specific state.
v) Passivated -
a) State - Bean becomes idle, its state is serialized to secondary storage.
b) Action - Container calls @PrePassivate before removing the bean from memory.
3. Example :
i) A shopping cart bean stores items selected by a user until checkout, maintaining state across
multiple interactions.
4.9) Write a Stateless Session Bean Code to Represent a BookInformation Entity?
//[Link]
import [Link];
@Remote
public interface BookBeanRemote {
String getBookDetails(String title, String author, double price);
}
[Link]
import [Link];
@Stateless
public class BookBean implements BookBeanRemote {
public String getBookDetails(String title, String author, double price) {
return "Book Title: " + title + "<br>Author: " + author + "<br>Price: $" + price;
}
}
//[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class BookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException {
[Link]("text/html");
PrintWriter out = [Link]();
try {
Context ctx = new InitialContext();
BookBeanRemote bean = (BookBeanRemote) [Link]("java:global/BookApp/
BookBean");
[Link]([Link]("Java EE", "James Gosling", 499.99));
} catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
Message-Driven Beans (Characteristics, Lifecycle and Diagram-4.11):
4.10) Explain the Characteristics and Working Principles of a Message-Driven Bean?
1. Definition :
i) Message-Driven Bean (MDB) - A special type of Enterprise Bean that processes asynchronous
messages sent via Java Message Service (JMS).
ii) Purpose - Used for background processing and decoupled communication between distributed
components.
2. Characteristics :
i) Asynchronous Processing -
a) MDBs - automatically receive and process messages from JMS queues or topics.
b) Clients - do not wait for a response (non-blocking).
ii) No Client Interaction -
a) MDBs - do not have remote or local interfaces.
b) Communication - happens only through the JMS provider.
iii) Transaction Support -
a) Container - manages transactions automatically during message processing.
b) Ensures - reliable delivery and rollback in case of failure.
iv) Security and Reliability -
a) Provides - secure message delivery between components.
b) Retries - failed message delivery automatically.
3. Working Principle :
i) A client or component - sends a message to a JMS destination (queue or topic).
ii) EJB Container - listens to the destination and activates an MDB instance.
iii) The MDB - receives the message and executes the onMessage() method.
iv) After processing - the container commits or rolls back the transaction as required.
4. Example :
i) Order system - uses an MDB to automatically process incoming orders placed in a JMS queue.
4.11) Explain the Lifecycle of a Message-Driven Bean using a Suitable Diagram?
1. Definition :
i) Message-Driven Bean (MDB) - A special type of Enterprise JavaBean that processes
asynchronous messages from JMS queues or topics.
ii) Purpose - Used for background tasks like order processing, email notifications, and real-time
data updates without client interaction.
2. Lifecycle of a Message-Driven Bean :
i) Does Not Exist -
a) State - MDB instance does not exist before creation.
b) Action - The EJB container creates MDB instances when the application starts or a message
arrives.
ii) Instantiated -
a) State - Container creates a new MDB instance using the default constructor.
b) Action - Resource injection and dependency setup are performed automatically.
iii) Initialized -
a) State - Bean is ready to receive messages.
b) Action - The @PostConstruct method is called for initialization (e.g., setting up resources).
iv) Ready (Message Handling) -
a) State - The bean is active and listens to a JMS queue or topic.
b) Action - The onMessage() method is invoked automatically when a message arrives.
v) Destroyed -
a) State - Bean instance is destroyed when the container shuts down or the application is
undeployed.
b) Action - The @PreDestroy method is called to release resources or close connections.
3. Diagram :
Does Not Exist
|
Instantiated
|
Initialized
|
Ready (onMessage)
|
Destroyed
JNDI (Naming and Directory services, Lookup, Injection-4.14):
4.12) Explain the Concepts of Naming and Directory Services, and Describe the Java Naming and
Directory Interface (JNDI)?
1. Definition :
i) Naming and Directory Services - Provide a way to locate and access resources like EJBs,
databases, or JMS using logical names instead of physical addresses.
ii) JNDI (Java Naming and Directory Interface) - A Java API that enables applications to connect
to naming and directory services for resource lookup in distributed systems.
2. Concepts of Naming and Directory Services :
i) Naming Service -
a) Maps - logical names to objects (e.g., EJB, DataSource).
b) Allows - easy access to resources using readable names.
ii) Directory Service -
a) Extends - naming services with attributes for each object.
b) Example - LDAP stores user info like email and role.
iii) Binding -
a) Associates - a name with an object in a naming service.
b) Example - Binding “java:comp/env/jdbc/MyDB” to a DataSource.
iv) Lookup -
a) Retrieves - resources by their logical names.
b) Example - Used in servlets to access EJBs or DB connections.
v) Context -
a) Represents - a namespace for bindings.
b) Used - to perform lookup and binding operations.
3. JNDI Architecture :
i) Application - Requests a resource using a logical name.
ii) JNDI API - Communicates with naming or directory services.
iii) SPI - Connects JNDI to systems like LDAP, DNS, or RMI.
4.13) Explain Basic Lookup in JNDI with an Example?
1. Definition :
i) JNDI (Java Naming and Directory Interface) - A Java API that allows applications to access
and look up resources like EJBs, DataSource, or JMS objects using logical names.
ii) Purpose - Provides a standard way for locating and accessing resources in distributed and
enterprise applications.
2. Concept of JNDI Lookup :
i) Naming Context -
a) Represents - a namespace where objects are registered and accessed.
b) Created - using InitialContext() to start the lookup process.
ii) Binding and Lookup -
a) Binding - associates a logical name with a resource in the context.
b) Lookup - retrieves the resource using its logical JNDI name.
iii) Resource Reference -
a) All resources - like EJBs, databases, and JMS components are bound to logical names in the
JNDI registry.
b) The application retrieves them dynamically without hardcoding connection details.
iv) Benefits -
a) Simplifies - resource access and management.
b) Enables - portability and reusability of applications.
3. Example :
import [Link].*;
import [Link];
import [Link].*;
public class JNDILookupExample {
public static void main(String[] args) {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) [Link]("java:comp/env/jdbc/MyDB");
Connection con = [Link]();
[Link]("Database Connection Established Successfully!");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
4.14) Explain Resource Injection in JNDI?
1. Definition :
i) Resource Injection - A process in which resources like DataSource, EJB, or JMS are
automatically provided (injected) by the container using annotations, instead of manually
performing lookups.
ii) Purpose - Simplifies resource access by eliminating explicit JNDI lookup code and improving
readability.
2. Working :
i) Annotation-Based Injection -
a) Uses - annotations such as @Resource, @EJB, or @PersistenceContext.
b) Container - automatically injects the defined resource at runtime.
ii) Resource Declaration -
a) Declared - in deployment descriptor ([Link]) or using annotations in code.
b) Mapped - to a JNDI name defined by the application server.
iii) Advantages -
a) Reduces - boilerplate lookup code.
b) Enhances - maintainability and readability.
c) Ensures - resources are configured and managed by the container.
3. Common Annotations :
i) @Resource -
a) Used - to inject a DataSource, JMS ConnectionFactory, or other resources.
b) Example -@Resource(name="jdbc/MyDB")
DataSource ds;
ii) @EJB -
a) Used - to inject Enterprise JavaBeans directly.
b) Example - @EJB
MyServiceBean service;
iii) @PersistenceContext -
a) Injects - an EntityManager for database operations.
b) Example - @PersistenceContext
EntityManager em;
4. Advantages :
i) Simplifies - resource management using annotations.
ii) Promotes - cleaner, more maintainable code.
iii) Avoids - manual lookups and configuration errors.
Interceptors(aroundinvoke(), Lifecycle-4.16):
4.15) What is an Interceptor? Explain how it is defined and how the aroundInvoke() method is
added to it?
1. Definition :
i) Interceptor - A special EJB class that executes code before or after business methods.
ii) Purpose - Handles cross-cutting concerns like logging, security, or transactions without
altering business logic.
2. Role of Interceptors :
i) Separation of Concerns - Keeps business logic clean and modular.
ii) Invocation Control - The @AroundInvoke method wraps logic around a business method.
3. Defining an Interceptor :
i) Step 1 - Create an Interceptor Class
a) Must have a method with @AroundInvoke.
b) Accepts InvocationContext and returns Object.
ii) Step 2 - Link with Bean
a) Use @Interceptors annotation on the EJB class.
b) The container automatically invokes interceptor logic.
4. Example :
//[Link]
import [Link].*;
@Interceptor
public class LogInterceptor {
@AroundInvoke
public Object log(InvocationContext ctx)throws Exception{
[Link]("Before: "+[Link]().getName());
Object res=[Link]();
[Link]("After: "+[Link]().getName());
return res;
}
}
//[Link]
import [Link].*;
import [Link];
@Stateless
@Interceptors([Link])
public class PaymentBean {
public void pay(){ [Link]("Processing Payment..."); }
}
4.16) Explain the Life Cycle of an Interceptor?
1. Definition :
i) Interceptor - A class in EJB used to execute additional logic before or after business methods.
ii) Lifecycle - Managed by the EJB container, defining how the interceptor is created, invoked, and
destroyed.
2. Interceptor Lifecycle Phases :
i) Instantiation -
a) The container - creates an instance of the interceptor when the EJB is initialized.
b) Only one instance - may be shared for multiple method invocations.
ii) Initialization -
a) The container - prepares the interceptor for method interception.
b) Resources - such as logging or monitoring tools may be initialized here.
iii) Invocation -
a) The @AroundInvoke method - is called before and after the EJB business method.
b) The InvocationContext - provides access to method details and parameters.
c) The method - continues execution using [Link]().
iv) Destruction -
a) The interceptor - is destroyed when the EJB instance is removed or the application shuts down.
b) Used - to release resources or perform cleanup operations.
3. Diagram :
Interceptor Created
Interceptor Initialized
@AroundInvoke (Before Method Execution After)
Interceptor Destroyed
4. Example :
i) @AroundInvoke executes both before and after the EJB method call.
ii) Useful for tasks like logging, transaction control, or performance monitoring.
Unit-V
Java Persistence (ORM, Impedance-5.3):
5.1) What is Persistence? Explain the Persistent Standards available in Java?
1. Definition :
i) Persistence - The ability of data to exist beyond the runtime of an application (stored
permanently in a database).
ii) Purpose - Allows Java objects to be stored, retrieved, and managed in databases without
manual SQL handling.
2. Need for Persistence :
i) Data - must survive program termination or server restart.
ii) Simplifies - data management in enterprise applications.
iii) Automates - object-to-database mapping and transaction handling.
3. Persistent Standards in Java :
i) JDBC (Java Database Connectivity) -
a) Provides - a standard API to connect Java programs with relational databases.
b) Limitation - Requires manual SQL coding and result mapping.
ii) JDO (Java Data Objects) -
a) Object-oriented API - for database-independent data storage.
b) Allows - transparent persistence of objects across databases.
c) Less popular - replaced by JPA in enterprise applications.
iii) JPA (Java Persistence API) -
a) A standard ORM (Object-Relational Mapping) API in Java EE.
b) Simplifies - data persistence using annotations and entity management.
c) Integrates - seamlessly with frameworks like Hibernate, EclipseLink.
4. Example :
i) JPA Entity class persists Java objects directly into a database table using annotations like
@Entity and @Id.
ii) Example - @Entity class Student { @Id int id; String name; } stores objects as database rows.
5.2) Why is there a need for Object Relational Mapping (ORM)?
1. Definition :
i) ORM (Object Relational Mapping) - A technique that maps Java objects to relational database
tables.
ii) Purpose - Simplifies data interaction by converting objects in Java to database records
automatically.
2. Need for ORM :
i) Object-Relational Gap -
a) Java - uses objects and classes, while databases use tables and rows.
b) ORM - bridges this structural mismatch between object-oriented and relational models.
ii) Reduces Manual SQL -
a) Developers - no longer need to write complex SQL queries.
b) ORM - automatically generates SQL for CRUD operations.
iii) Increases Productivity -
a) Simplifies - database operations using Java methods.
b) Allows - faster development with less boilerplate code.
iv) Database Independence -
a) ORM tools - like Hibernate or JPA work with multiple databases.
b) Applications - become portable without changing SQL syntax.
v) Transaction and Caching Support -
a) Handles - transactions automatically with rollback and commit.
b) Improves - performance through built-in caching mechanisms.
vi) Maintains Data Integrity -
a) ORM frameworks - ensure consistent data mapping using metadata and annotations.
b) Reduces - chances of programming or SQL mapping errors.
3. Example :
i) In Hibernate, an entity class like Student is directly mapped to a database table using @Entity.
ii) The framework auto-generates queries for storing, updating, or deleting objects.
5.3) What is Impedance Mismatch in the Context of ORM, and How Can It Be Solved?
1. Definition :
i) Impedance Mismatch - The conflict between object-oriented programming (OOP) concepts in
Java and relational database (RDBMS) structures.
ii) Occurs - Because objects use inheritance, relationships, and encapsulation, while databases
use tables, columns, and foreign keys.
2. Causes of Impedance Mismatch :
i) Data Representation -
a) Objects - represent data as attributes and methods.
b) Databases - store data in tables and rows.
ii) Relationships -
a) OOP - uses references and associations between objects.
b) RDBMS - uses primary and foreign keys for relationships.
iii) Inheritance -
a) Java supports - class hierarchies and polymorphism.
b) Databases - have no direct equivalent for inheritance structures.
iv) Identity -
a) Objects - are identified by memory references.
b) Databases - identify records using primary keys.
v) Data Navigation -
a) Objects - use pointers and method calls.
b) Databases - use joins and queries for navigation.
3. Solution (Using ORM Frameworks) :
i) ORM Tools (like Hibernate, JPA) -
a) Automatically map - classes to tables and attributes to columns.
b) Manage - relationships using annotations (@OneToMany, @ManyToOne).
ii) Inheritance Mapping -
a) Provides - strategies like single table, joined table, and table-per-class.
iii) Identity Mapping -
a) Uses - annotations like @Id and @GeneratedValue to sync Java and database identifiers.
iv) Query Abstraction -
a) Uses - HQL or JPQL instead of SQL to access objects directly.
Java Persistence API (Architecture with Diagram, Works-5.6):
5.4) Explain the Java Persistence API (JPA) with its Specifications?
1. Definition :
i) JPA (Java Persistence API) - A standard specification in Java EE for managing relational data
using object-relational mapping (ORM).
ii) Purpose - Simplifies data persistence by allowing developers to interact with databases
through Java objects instead of SQL queries.
2. Key Features of JPA :
i) ORM Mapping -
a) Maps - Java classes to database tables using annotations like @Entity, @Table, and @Column.
b) Eliminates - the need for manual SQL handling.
ii) Entity Management -
a) The EntityManager interface - handles CRUD operations on entity objects.
b) Manages - object states such as new, managed, detached, and removed.
iii) Query Language -
a) JPQL (Java Persistence Query Language) - provides an object-oriented way to write database
queries.
b) Supports - filtering, joins, and aggregation using entity fields.
iv) Transaction Management -
a) JPA integrates - with Java Transaction API (JTA) for atomic and consistent operations.
b) Ensures - rollback on failure and commit on success.
v) Caching and Performance -
a) Supports - first-level (session) and second-level (shared) caching.
b) Improves - performance by reducing database access.
3. JPA Specifications :
i) Defines - annotations and interfaces for persistence (Entity, EntityManager, PersistenceUnit).
ii) Allows - vendor implementations like Hibernate, EclipseLink, and OpenJPA to provide actual
functionality.
iii) Provides - standardized persistence context for managing entities.
5.5) Draw and Explain the Architecture of JPA?
1. Definition :
i) JPA (Java Persistence API) - A framework specification that provides an abstraction for
database operations using ORM.
ii) Purpose - Simplifies interaction between Java objects and relational databases through entity
management.
2. JPA Architecture Components :
i) Entity -
a) Represents - a database table.
b) Each instance - corresponds to a row.
ii) Persistence Unit -
a) Defined - in [Link] with configuration details.
b) Includes - provider, URL, username, password, and driver.
iii) EntityManager -
a) Core interface - for CRUD operations (persist(), find(), remove(), merge()).
b) Manages - entity lifecycle within persistence context.
iv) EntityManagerFactory -
a) Creates - and manages multiple EntityManager instances.
b) Provides - thread-safe persistence management.
v) Persistence Provider -
a) Implementation - of JPA (e.g., Hibernate, EclipseLink).
b) Handles - mapping, SQL generation, and transactions.
vi) Persistence Context -
a) Acts - as a cache for entity instances.
b) Ensures - synchronization and uniqueness within transactions.
vii) Database -
a) Stores - entity data.
b) Communicates - through SQL generated by the provider.
3. Diagram :
Java Application
|
EntityManagerFactory
|
EntityManager(Handles Entity Objects)
|
Persistence Provider(e.g., Hibernate, JPA)
|
Database
5.6) Explain How JPA Works and Where It Fits into the Java EE Ecosystem?
1. Definition :
i) JPA (Java Persistence API) - A Java EE specification for managing relational data using
objects.
ii) Purpose - Persists Java objects into databases without complex SQL.
2. Working of JPA :
i) Entity Definition -
a) Java classes - annotated with @Entity represent database tables.
b) Fields map - to columns using @Column annotations.
ii) Configuration ([Link]) -
a) Defines - persistence unit, database details, and JPA provider (e.g., Hibernate, EclipseLink).
b) Located - inside the META-INF folder for application-wide access.
iii) EntityManagerFactory -
a) Created - using [Link]("unitName").
b) Provides - EntityManager instances for database operations.
iv) EntityManager -
a) Performs - CRUD operations (persist(), find(), remove(), merge()).
b) Manages - entity lifecycle (new, managed, detached, removed).
v) Persistence Context -
a) Acts - as a cache for managing entity instances during a transaction.
b) Synchronizes - entity state changes with the database upon commit.
vi) Transaction Management -
a) Uses - Java Transaction API (JTA) for atomic and reliable operations.
b) Ensures - rollback in case of errors or failures.
3. JPA in the Java EE Ecosystem :
i) Integration -
a) Works - seamlessly with EJB, Servlets, JSP, and RESTful APIs.
b) Supports - distributed, transactional enterprise applications.
ii) Compatibility -
a) Supports - container-managed transactions and dependency injection.
b) Integrates - with JMS, JTA, and JNDI services.
iii) Providers -
a) Common - Hibernate, EclipseLink, OpenJPA.
b) Supported - across Java EE servers like GlassFish, WildFly, and TomEE.
Hibernate Framework(Features, Advantages, Architecture with Diagram, Structure and
Components, Process-5.11):
5.7) What is Hibernate? Explain its Features and Advantages?
1. Definition :
i) Hibernate - An open-source ORM (Object Relational Mapping) framework for Java.
ii) Purpose - Maps Java objects to database tables, simplifying database operations.
2. Features of Hibernate :
i) ORM Support -
a) Maps - Java classes to database tables.
b) Removes - the need for manual SQL handling.
ii) Automatic Table Generation -
a) Creates - tables and relationships automatically.
b) Simplifies - database setup and management.
iii) HQL (Hibernate Query Language) -
a) Provides - object-oriented query language similar to SQL.
b) Supports - joins, filters, and aggregation using entity fields.
iv) Caching -
a) Offers - first and second-level caching.
b) Improves - performance by minimizing database calls.
v) Transaction Management -
a) Integrates - with JDBC and JTA for safe transactions.
b) Ensures - rollback and consistency in case of failure.
vi) Portability -
a) Supports - multiple databases with minimal configuration.
b) Works - across different application servers.
vii) Lazy Loading -
a) Loads - data only when required.
b) Reduces - memory usage for large datasets.
viii) Relationship Mapping -
a) Supports - one-to-one, one-to-many, many-to-many mappings.
b) Simplifies - complex data relationships using annotations.
3. Advantages of Hibernate :
i) Reduces - development time with automatic CRUD operations.
ii) Increases - application portability and maintainability.
iii) Simplifies - data handling and transaction management.
iv) Integrates - easily with Spring and JPA frameworks.
5.8) Draw and Explain the Architecture of the Hibernate Framework?
1. Definition :
i) Hibernate - A Java ORM framework that maps Java objects to relational database tables.
ii) Purpose - Simplifies data access, query execution, and transaction management.
2. Hibernate Architecture Components :
i) Configuration -
a) Reads - settings from [Link].
b) Builds - SessionFactory using configuration properties.
ii) SessionFactory -
a) Creates - Session objects for database interaction.
b) Manages - database connection and metadata.
iii) Session -
a) Represents - a single communication between app and database.
b) Performs - CRUD and persistence operations.
iv) Transaction -
a) Ensures - atomic, consistent operations.
b) Supports - commit and rollback.
v) Query -
a) Executes - HQL or SQL queries.
b) Fetches - data using object-oriented syntax.
vi) Persistent Objects -
a) Represent - Java entities mapped to database tables.
b) Managed - automatically by Hibernate.
vii) Cache -
a) Provides - first and second-level caching.
b) Enhances - performance by reducing DB access.
3. Diagram :
Java Application
!
Hibernate API
!
Core Components (SessionFactory, Transaction)
!
Database Server
5.9) Explain the Different Components of Hibernate?
1. Definition :
i) Hibernate - An ORM framework that automates database operations in Java.
ii) Purpose - Provides a structured way to map Java objects to database tables and manage
persistence efficiently.
2. Components of Hibernate :
i) Configuration -
a) Reads - database settings and mappings from [Link].
b) Builds - SessionFactory to connect with the database.
ii) SessionFactory -
a) A factory - for creating Session objects.
b) Stores - configuration, mapping, and connection details.
iii) Session -
a) Represents - a single unit of work (interaction with DB).
b) Performs - CRUD operations and manages entity states.
iv) Transaction -
a) Maintains - atomicity and consistency of database actions.
b) Supports - commit and rollback.
v) Query -
a) Used - for fetching and manipulating data.
b) Supports - HQL, SQL, and Criteria API queries.
vi) Criteria API -
a) Provides - object-oriented query creation.
b) Enables - dynamic query building without hardcoded SQL.
vii) Persistent Objects -
a) Represent - entities mapped to database tables using annotations (@Entity, @Id).
b) Managed - by Hibernate within sessions.
viii) Cache -
a) Provides - first-level (Session) and second-level (SessionFactory) caching.
b) Enhances - performance by minimizing repeated queries.
3. Example :
i) Configuration loads DB settings.
ii) SessionFactory creates session.
iii) Session performs CRUD.
iv) Transaction ensures atomic updates.
5.10) Explain the Structure and Components of the Hibernate Configuration File
([Link])?
1. Definition :
i) [Link] - The main configuration file for Hibernate.
ii) Purpose - Defines database connection settings, mapping resources, and Hibernate properties
needed for ORM operations.
2. Structure and Components :
i) Root Element -
a) <hibernate-configuration> - Root tag enclosing the entire configuration.
b) <session-factory> - Contains all Hibernate settings and mappings.
ii) Database Connection Properties -
a) <property name="[Link].driver_class"> – Specifies the JDBC driver (e.g.,
[Link]).
b) <property name="[Link]"> – Defines database URL (e.g., jdbc:mysql://
localhost:3306/testdb).
c) <property name="[Link]"> – Database username.
d) <property name="[Link]"> – Database password.
iii) Hibernate Dialect -
a) <property name="[Link]"> – Informs Hibernate which SQL dialect to use (e.g.,
[Link]).
iv) Connection Pool and Driver Management -
a) <property name="[Link].pool_size"> – Defines the number of database
connections in the pool.
v) Auto Schema Generation -
a) <property name="[Link]"> – Defines schema strategy (create, update,
validate, or none).
vi) SQL Logging -
a) <property name="hibernate.show_sql"> – Displays generated SQL queries in the console.
b) <property name="hibernate.format_sql"> – Formats SQL output for readability.
5.11) Explain the General Process (Modus Operandi) Behind a Hibernate Application?
1. Definition :
i) Hibernate - A Java-based ORM framework that maps Java classes to database tables.
ii) Purpose - Simplifies database operations using objects instead of direct SQL queries.
2. Process of Hibernate Application :
i) Configuration Setup -
a) Define - database connection and mapping details in [Link].
b) Load - configuration using the Configuration class.
ii) Build SessionFactory -
a) SessionFactory - created from configuration for managing sessions.
b) Stores - database connection and mapping metadata.
iii) Open Session -
a) Session - acts as a single unit of work between application and database.
b) Created - using [Link]().
iv) Begin Transaction -
a) Start - transaction using [Link]().
b) Ensures - atomic and consistent database operations.
v) Perform Operations -
a) Use - Hibernate methods like save(), update(), delete(), and get().
b) Maps - Java objects automatically to database tables.
vi) Commit and Close -
a) Commit - transaction using [Link]().
b) Close - session using [Link]() to release resources.
vii) SQL Generation -
a) Hibernate - automatically converts object operations into SQL.
b) Executes - queries internally without manual SQL coding.
3. Example :
i) Flow - Configuration SessionFactory Session Transaction CRUD Operation
Commit Close.
Advanced JPA & JPQL(JOIN, CDI, Functios, Downcasting-5.14):
5.12) Explain the JOIN Condition Using ON in JPQL?
1. Definition :
i) JPQL (Java Persistence Query Language) - A query language used to perform database
operations on entity objects instead of tables.
ii) JOIN with ON - Used to combine data from multiple entities based on a relationship condition.
2. Purpose :
i) Retrieves - related data from multiple entities efficiently.
ii) Works - similar to SQL joins but operates on entity relationships.
3. Types of Joins in JPQL :
i) INNER JOIN -
a) Returns - records with matching values in both entities.
b) Example -
SELECT s FROM Student s INNER JOIN [Link] d ON [Link] = [Link]
ii) LEFT JOIN -
a) Returns - all records from the left entity and matching ones from the right.
b) Example -
SELECT s FROM Student s LEFT JOIN [Link] d ON [Link] = [Link]
iii) RIGHT JOIN -
a) Returns - all records from the right entity and matching ones from the left.
b) Example -
SELECT d FROM Department d RIGHT JOIN [Link] s ON [Link] = [Link]
4. Working :
i) JPQL - uses entity relationships (mapped by annotations like @OneToMany or @ManyToOne).
ii) The ON clause - defines explicit join conditions when automatic mapping is not available.
iii) Returns - entity objects instead of raw table data.
5.13) Explain Entity Listeners Using CDI?
1. Definition :
i) Entity Listeners - Special callback classes in JPA used to listen to entity lifecycle events like
persist, update, or delete.
ii) CDI (Contexts and Dependency Injection) - Integrates with entity listeners to inject services or
beans for handling these events dynamically.
2. Purpose :
i) Automates - tasks like auditing, logging, or validation during entity lifecycle changes.
ii) Provides - separation of business logic from entity classes for cleaner design.
3. Lifecycle Events Supported :
i) @PrePersist - Triggered before an entity is saved to the database.
ii) @PostPersist - Triggered after the entity is saved.
iii) @PreUpdate - Called before updating an entity.
iv) @PostUpdate - Called after an update.
v) @PreRemove - Triggered before deletion.
vi) @PostRemove - Triggered after deletion.
vii) @PostLoad - Executed after loading an entity from the database.
4. Working :
i) The listener - automatically triggers when entity lifecycle events occur.
ii) CDI - injects dependencies like services or loggers into listeners.
iii) The entity - stays clean while the listener manages background operations.
5. Summary :
i) Entity listeners - enhance modularity and maintainability.
ii) CDI integration - provides dependency management and reusability of listener logic.
5.14) Write a Short Note on Functions and Downcasting in JPQL?
1. Definition :
i) JPQL (Java Persistence Query Language) - Used in JPA to query entities using object-oriented
syntax.
ii) Purpose - Functions perform operations on data, and downcasting allows access to subclass
fields.
2. JPQL Functions :
i) String Functions -
a) Used - for text manipulation.
b) Examples - CONCAT(), LOWER(), SUBSTRING().
c) Example - SELECT CONCAT(e.firstName, ' ', [Link]) FROM Employee e
ii) Numeric Functions -
a) Used - for mathematical operations.
b) Examples - ABS(), MOD(), ROUND().
c) Example - SELECT ROUND([Link]) FROM Product p
iii) Date/Time Functions -
a) Used - to manage date and time values.
b) Examples - CURRENT_DATE, CURRENT_TIMESTAMP.
c) Example - SELECT e FROM Event e WHERE [Link] > CURRENT_DATE
iv) Aggregate Functions -
a) Used - for calculations on groups of data.
b) Examples - COUNT(), SUM(), AVG(), MIN(), MAX().
c) Example - SELECT AVG([Link]) FROM Employee e
3. Downcasting in JPQL :
i) Used - to access subclass-specific fields using TREAT().
ii) Example -
SELECT TREAT(e AS FullTimeEmployee).bonus FROM Employee e
4. Summary :
i) Functions - Simplify text, numeric, and date operations.
ii) Downcasting - Enables subclass access in inheritance hierarchies.
iii) Together - Make JPQL expressive and object-oriented.
Practical ORM (Guest, Visitor Feedback-5.16):
5.15) Write a JSP Code to Add Guest Feedback to a Database Table Using JPA?
// [Link]
import [Link].*;
@Entity
public class Feedback {
@Id @GeneratedValue
private int id;
private String name, email, message;
// Getters and Setters
}
<!-- [Link] -->
<persistence version="2.1">
<persistence-unit name="FeedbackPU">
<class>Feedback</class>
<properties>
<property name="[Link]" value="jdbc:mysql://localhost:3306/testdb"/>
<property name="[Link]" value="root"/>
<property name="[Link]" value="password"/>
<property name="[Link]" value="[Link]"/>
<property name="[Link]" value="update"/>
</properties>
</persistence-unit>
</persistence>
<!-- [Link] -->
<form action="[Link]" method="post">
Name:<input name="name"><br>
Email:<input name="email"><br>
Message:<textarea name="message"></textarea><br>
<input type="submit" value="Submit">
</form>
<!-- [Link] -->
<%@ page import="[Link].*,Feedback" %>
<%
EntityManager em =
[Link]("FeedbackPU").createEntityManager();
[Link]().begin();
Feedback f = new Feedback();
[Link]([Link]("name"));
[Link]([Link]("email"));
[Link]([Link]("message"));
[Link](f);
[Link]().commit();
[Link]("Feedback Submitted!");
[Link]();
%>
5.16) Write a JSP code to add visitor's feedback to a database table using Hibernate?
// [Link]
import [Link].*;
@Entity
public class VisitorFeedback {
@Id @GeneratedValue
private int id;
private String name, email, comment;
// Getters and Setters
}
<!-- [Link] -->
<hibernate-configuration>
<session-factory>
<property name="[Link]">jdbc:mysql://localhost:3306/testdb</property>