KEMBAR78
Unit 1 Notes A | PDF | Java (Programming Language) | World Wide Web
0% found this document useful (0 votes)
5 views56 pages

Unit 1 Notes A

The document discusses Enterprise Applications, defining them as large-scale software aimed at solving organizational problems and detailing the Java Platform, Enterprise Edition (Java EE) as a framework for server-side applications. It outlines the challenges in developing these applications, emphasizing the need for security, accessibility, and integration with existing systems. Additionally, it provides an overview of various technologies within the Java EE platform, including web application technologies and the evolution of Java EE into Jakarta EE under the Eclipse Foundation.

Uploaded by

raiayushrai2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views56 pages

Unit 1 Notes A

The document discusses Enterprise Applications, defining them as large-scale software aimed at solving organizational problems and detailing the Java Platform, Enterprise Edition (Java EE) as a framework for server-side applications. It outlines the challenges in developing these applications, emphasizing the need for security, accessibility, and integration with existing systems. Additionally, it provides an overview of various technologies within the Java EE platform, including web application technologies and the evolution of Java EE into Jakarta EE under the Eclipse Foundation.

Uploaded by

raiayushrai2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit 1

Chapter 1
1. What is an Enterprise Application? What is the enterprise edition of Java?
Answer:
Enterprise application:
• Enterprise application software is large-scale software that is aimed to support or solve
the problems of an entire organization.
• This large-scale software allows for several different user roles, and the roles define the
actions that specific user can perform.
• An enterprise application is a business application.
• As most people use the term, it is a big business application. In today’s corporate environment,
enterprise applications are complex, scalable, distributed, component-based, and mission-
critical.
• They may be deployed on a variety of platforms across corporate networks, intranets,
or the Internet.
• They are data-centric, user-friendly, and must meet stringent requirements for security,
administration, and maintenance. In short, they are highly complex systems.
• The enterprise software includes many functions and abilities:
o Salespeople can log client information, including personal and product information
and client location in the sales pipeline.
o Customer service representatives can track client issues and communication alongside
internal responses and updates.
o Internal-facing employees can take client specifications to build the product.
o Managers and C-level executives can track client and employee performance.
Enterprise Edition:
• The Java Platform, Enterprise Edition (Java EE) is a collection of Java APIs owned by Oracle
that software developers can use to write server-side applications. It was formerly known as
Java 2 Platform, Enterprise Edition, or J2EE.
• The J2EE is not a product, rather it is a specification defining a server-side Java framework.
• Vendors are responsible for using this J2EE spec in order to make compliant J2EE Servers.
This allows IT developers to write their Java Business Logic using the J2EE APIs. They do
not have to worry about implementing the surrounding framework.
• It combines a number of technologies in one architecture with a comprehensive Application
Programming Model and Compatibility Test Suite for building enterprise-class server-side
applications.
• Java EE applications are hosted on application servers, such as IBM's WebSphere,
Oracle's GlassFish or Red Hat's WildFly server, all of which run either in the cloud or
within a corporate data center.
• While Java EE apps are hosted on the server side, examples of Java EE clients include
an internet of things (IoT) device, smartphone, RESTful web service, standard web-
based application, WebSocket or even microservices running in a Docker container.
• Java EE provides collection of:
o Standardized components that facilitates the crafting of commercial applications
o Standard interfaces that define how the various application modules interconnect
o Standard services that define how the different software modules communicate

ADITI CHIKHALIKAR 1
Extra:
Client Type Description Example
IoT device Sensors, appliances, or embedded A temperature sensor posting data to
devices sending data a Java EE REST API
Smartphone Mobile apps that need backend Android/iOS app fetching user data
services from a Java EE app
Web-based Browsers accessing Java EE via A shopping cart in a browser
application HTML/JS UI communicating with Java EE
RESTful web Other services/apps using Payment gateway consuming REST
service HTTP/JSON to interact API exposed by Java EE
WebSocket client Real-time communication Chat app or live stock ticker
between client & server
Microservices in Lightweight Java or non-Java A Python service in Docker calling a
Docker services in containers Java EE microservice

Aspect Description
Java EE ServerRuns the main application logic (on WebSphere, WildFly, etc.)
Hosting Cloud or on-premise data centers
Clients Anything that needs the data or services — IoT, mobile apps, web browsers,
REST clients, etc.
Communication Via REST APIs, WebSocket, JMS, or service calls

A smart home application:


• IoT device (Smart thermostat) → Sends temperature data
• Mobile App → Displays temperature, allows changes
• Java EE App (running on WildFly in AWS Cloud) → Receives data, stores it in DB, exposes
REST API
• Web client → Uses JavaScript to display real-time updates via WebSockets

2. What are the challenges of Enterprise Application Development?


Answer:
• The principal challenge is to maintain the value of existing business with the Internet's hyper-
competitive pace.
• To achieve a competitive edge, time and quality plays an important role. By keeping the
following factors in view, a developer can deliver customized enterprise applications quickly:
⮚ Programming Productivity
⮚ Response to Demand
⮚ Integration with Existing Systems
⮚ Freedom to Choose
⮚ Maintaining Security
• One of the key objectives of the Java EE platform is to provide a standard environment to
develop Enterprise Applications.
• The Java EE platform has been influenced by many earlier initiatives. One of those was
Microsoft's successful integration of technologies for all three tiers Visual Basic, Microsoft
Transaction Server [MTS] and SQL Server.

ADITI CHIKHALIKAR 2
• Enterprise mobility has become the need of the hour. With more people bringing in their own
devices to work, it is necessary to ensure enterprise application are developed for people for
people to envision productivity and efficiency sailing through the whole enterprise.

• Security is an important concern with enterprise mobility, and it is important to take security
as a priority when developing enterprise application. The aim is to reduce the cost of your
enterprise, by giving it more scalability and flexibility. The whole environment should be
virtual and enable availability of data in real-time.

• Accessibility: Key decision makers within the organization need data to make informed
decisions. They need to know what is happening, and what will affect their decisions, which
makes data availability crucial to them. Making the data available and accessible in remote
locations becomes essential at such a time. Accessibility is a major challenge for the
enterprises, so that they can make informed & fast decisions.

3. What is Java Enterprise Edition (Java EE)? Explain.


Answer:

• The Java Platform, Enterprise Edition (Java EE) is a collection of Java APIs owned by
Oracle that software developers can use to write server-side applications. It was
formerly known as Java 2 Platform, Enterprise Edition, or J2EE.
• The J2EE is not a product, rather it is a specification defining a server-side Java
framework.
• Java EE is a set of coordinated technologies and practices that enable developing,
deploying and managing multi-tier Server centric enterprise applications.
• It is a collection of standardized components, containers and services for creating and
deploying distributed applications.
• Java EE has brought in powerful set of APIs that has helped the developers to reduce the
development time and application complexity but also improve the application
performance.
• Commercial applications that have to function at this level do not run on a single PC as they
require significantly more computing power and throughput than what a single PC can
provide.

ADITI CHIKHALIKAR 3
• The commercial application is normally sectioned into functional segments, each such
segment bound to a specific Master or Child business process at a specific location, then
deployed on appropriate hardware platform(s) at that location.
• Finally, the business data generated and manipulated at that location would be streamed and
integrated into one central point say for example Enterprise headquarters. This is the essence
of distributed computing.
• Java EE provides a collection of:
⮚ Standardize components that facilitate the crafting of such commercial applications.
⮚ Standard interfaces that define how various application modules interconnect.
⮚ Standard services that define how the different software modules communicate.
• Finally, Java's Write Once, Run Anywhere [WORA] philosophy has provided a basis for
tying together the many technologies that are required to develop and deploy enterprise
based commercial applications.
• Java EE significantly reduces the cost and complexity of developing and deploying multi-
tier solutions, resulting in services that can be rapidly deployed and easily enhanced.

4. What are different technologies provided by Java EE platform?


Answer:

Web Enterprise Web


Security
Applications Applications Services
Technologies
Technologies Technologies Technologies
Enterprise
Java Servlet JavaBeans [EJB] Java
Java Persistence Authorization
JavaServer Pages SOAP and
API [JPA] Contract for
[JSP] RESTful
Containers
Java Transaction [JACC]
JavaServer Pages API [ITA]
Standard Tag Java Message
Library [JSTL] Service [JMS]
Java
Java EE Authentication
JavaServer Faces Java API for
Connector Service Provider
[JSF] XML Registries
Architecture Interface for
[JAXR]
Containers
Facelets [JASPIC]
JavaMail

Web Applications Technologies


• Java Servlet: A Servlet is a program that extends the functionality of a Web server. Servlets
receive a request from a client, dynamically generate the response and then send the response
containing an HTML or XML document to the client. Java Servlet technology allows defining
HTTP specific Servlet classes.
• JavaServer Pages [JSP]: JavaServer Pages [JSP] technology helps to generate dynamic
content for a Web client. A JSP page is a text-based document that contains two types of text:
o Static data: Can be expressed in any text-based format such as HTML, WML and
XML
o JSP elements: Informs how the page constructs dynamic content

ADITI CHIKHALIKAR 4
• JavaServer Pages Standard Tag Library [JSTL]: JavaServer Pages Standard Tag Library
[JSTL] encapsulates core functionality of JSP applications. This technology allows creating a
standard set of tags, instead of mixing tags from numerous vendors in a JSP application. This
standardization allows deploying applications on any JSP server that supports JSTL. JSTL
has iterator and conditional tags for handling flow control, tags for manipulating XML
documents, internationalization tags, tags for accessing databases using SQL and commonly
used functions.
• JavaServer Faces [JSF]: JavaServer Faces (JSF) is a user interface framework for building
Web applications.
• Facelets: Facelets refers to JavaServer Faces ViewDefinition Framework, which is a page
declaration language developed for use with JavaServer Faces technology. The concept of
View Declaration Language [VDL] allows declaration of UI components in different
presentation technologies.

Enterprise Applications Technologies


• Enterprise JavaBeans [EJB]: An Enterprise JavaBean [EJB] component is an enterprise
bean having methods to implement modules of business logic. They are scalable,
transactional, secure and are building blocks of the enterprise application running on Java EE
server. EJBS can be accessed locally and remotely through RMI or HTTP for SOAP and
RESTful web services.
• Java Persistence API [JPA]: Java Persistence API (JPA) is a Java standards-based API for
Object-Relational Mapping [ORM], a solution for persistence. Persistence uses an object-
relational mapping approach to bridge the gap between an object oriented model and a
relational database. Java Persistence consists of: The Java Persistence API, The query
language, Object/relational mapping metadata
• Java Transaction API [ITA]: Java Transaction API [JTA] provides a standard interface for
demarcating transactions.
• Java Message Service [JMS]: Java Message Service [JMS] API is a messaging standard that
allows Java EE application components to create, send, receive and read messages. It enables
distributed communication that is loosely coupled, reliable and asynchronous.
• Java EE Connector Architecture: Java EE Connector Architecture is used by tools vendors
and system integrators to create resource adapters that support access to Enterprise
Information Systems that can be plugged into any Java EE product.
• JavaMail: Java EE platform includes JavaMail with a service provider interface that allows
application components to send emails.

Web Services Technologies


• SOAP and RESTful: Java EE provides support for SOAP and RESTful web services. Java
API for RESTful Web Services (JAX-RS] defines APIs for the development of Web services
built according to the Representational State Transfer [REST] architectural style. Java API
for XML-Based Web Services [JAX-WS] provides support for web services using the
SOAP/HTTP protocol.
• Java API for XML Registries [JAXR]: Java API for XML Registries [JAXR] allows
accessing business and general-purpose registries over the Web.

Security Technologies
• Java Authorization Contract for Containers [JACC]: Java Authorization Contract for
Containers [JACC] specification defines a contract between a Java EE application server and

ADITI CHIKHALIKAR 5
an authorization policy provider. JACC enables services to authenticate and enforce access
controls upon users. All Java EE containers support this contract.
• JASPIC: Java Authentication Service Provider Interface for Containers [JASPIC]
specification defines a Service Provider Interface [SPI] by which authentication providers that
implement message authentication mechanisms may be integrated in client or server message
processing containers or runtimes.

5. Explain Web Application Technologies in detail?


Answer:

Web Applications Technologies

• Java Servlet: A Servlet is a program that extends the functionality of a Web server. Servlets
receive a request from a client, dynamically generate the response and then send the response
containing an HTML or XML document to the client. Java Servlet technology allows defining
HTTP specific Servlet classes.
• JavaServer Pages [JSP]: JavaServer Pages [JSP] technology helps to generate dynamic
content for a Web client. A JSP page is a text-based document that contains two types of text:
o Static data: Can be expressed in any text-based format such as HTML, WML and
XML
o JSP elements: Informs how the page constructs dynamic content
• JavaServer Pages Standard Tag Library [JSTL]: JavaServer Pages Standard Tag Library
[JSTL] encapsulates core functionality of JSP applications. This technology allows creating a
standard set of tags, instead of mixing tags from numerous vendors in a JSP application. This
standardization allows deploying applications on any JSP server that supports JSTL. JSTL
has iterator and conditional tags for handling flow control, tags for manipulating XML
documents, internationalization tags, tags for accessing databases using SQL and commonly
used functions.
• JavaServer Faces [JSF]: JavaServer Faces (JSF) is a user interface framework for building
Web applications.
• Facelets: Facelets refers to JavaServer Faces ViewDefinition Framework, which is a page
declaration language developed for use with JavaServer Faces technology. The concept of
View Declaration Language [VDL] allows declaration of UI components in different
presentation technologies.

6. Give Brief information about JavaEE Evolution?


Answer:
⮚ Java EE is a robust platform for building enterprise-level applications.
⮚ It extends Java SE with APIs and tools required for multi-tiered, distributed, and web-
based applications.
⮚ Java EE builds on Java SE’s core strengths — platform independence, advanced object-
oriented capabilities, and strong memory management through garbage collection. It also adds
enterprise features like running apps across multiple computers (distributed computing) and
organizing them into layers (multi-tier architecture) for better performance and scalability.
⮚ It provides a standardized, modular components approach and a declarative way to define
component behaviour to reduce programming effort and improve developer productivity.

ADITI CHIKHALIKAR 6
⮚ The original J2EE specification was developed by Sun Microsystems, and J2EE 1.2 was
designed to support distributed enterprise systems.
⮚ Java EE was formerly known as J2EE (Java 2 Platform, Enterprise Edition). The name
was changed to Java EE starting from version 5. The last version released by Oracle is
Java EE 8.
⮚ Java EE is now owned and managed by the Eclipse Foundation under the new name
Jakarta EE. When Oracle handed over Java EE to the Eclipse Foundation in 2017, they
retained the trademark "Java", so the platform was renamed to Jakarta EE.
⮚ On 28th May, 2013 Oracle released Java EE7
⮚ Enhanced HTML5 support
⮚ Increased developer productivity
⮚ Improvements on how enterprise demands can be met.

Java EE 8: Key features, Specifications

Version Release Key Features


Year
J2EE 1.2 1999 Initial release by Sun Microsystems, focused on distributed
computing
J2EE 1.3 2001 Introduction of Java Community Process, support for XML
J2EE 1.4 2002 Focus on web services, JAX-RPC, Servlet 2.4
Java EE 5 2006 Major shift from J2EE to Java EE, annotations, EJB 3.0, simplified
development
Java EE 6 2009 Profiles (like Web Profile), extensibility, support for third-party
frameworks
Java EE 7 2013 Enhanced HTML5, WebSocket, JSON-P, improved productivity
Java EE 8 2017 Focus on cloud, microservices, HTTP/2, JSON-B, CDI 2.0, Security
API

ADITI CHIKHALIKAR 7
Time Owner Name
Period
Before 2010 Sun Microsystems J2EE (Java 2 Platform, Enterprise
Edition)
2010–2017 Oracle Corporation (after acquiring Java EE (Java Platform, Enterprise
Sun) Edition)
2017–Now Eclipse Foundation Jakarta EE

⮚ J2EE 1.2 (1999)


• First official enterprise version.
• Targeted distributed computing—systems where parts run on different machines but work
together.
• Introduced core APIs like Servlets, JSP, and EJB (Enterprise JavaBeans).
[Distributed Computing: Applications run across multiple systems connected via a network,
improving reliability and scalability.]

⮚ J2EE 1.3 (2001)


• Adopted Java Community Process (JCP) to standardize APIs via community input.
• Introduced Java Message Service (JMS) and JavaMail API.
• Better support for XML-based web services.
[JCP (Java Community Process): A formal process that allows Java developers, companies, and
organizations to participate in defining future Java technologies.]

⮚ J2EE 1.4 (2002)


• Focused on interoperability and web services.
• Added support for SOAP, WSDL, and JAX-RPC for remote procedure calls via XML.
[Web Services: Software systems designed to support interoperable machine-to-machine interaction
over a network.]

⮚ Java EE 5 (2006)
• Renamed from J2EE to Java EE.
• Major shift toward simplified development:
o Introduced annotations (e.g., @EJB, @Resource) to reduce XML configuration.
o Enhanced EJB 3.0 — simplified enterprise beans.
o Improved integration between components.
[Annotations: Metadata used in Java to reduce boilerplate code ["Boilerplate code" refers to standard
or template code that you often must write repeatedly in a specific programming language or
framework before you can start working on the actual logic of your application.] and automate tasks
like configuration or dependency injection.]

⮚ Java EE 6 (2009)
• Introduced Profiles: lighter subsets of Java EE APIs, such as Web Profile for web
applications.
• Enhanced support for third-party frameworks like Spring and Hibernate.
• Introduced Contexts and Dependency Injection (CDI).
[CDI: A framework for managing object lifecycles and injecting dependencies, allowing for more
loosely coupled and testable code.]

ADITI CHIKHALIKAR 8
⮚ Java EE 7 (2013)
• Focused on:
o HTML5 support (for modern web UIs)
o WebSocket API (real-time communication)
o JSON Processing (JSON-P) for handling JSON data
• Better scalability and productivity for enterprise developers.
[WebSocket: Enables full-duplex communication channels over a single TCP connection (ideal for
live data apps like chats or trading).]

⮚ Java EE 8 (2017)
• Final version under Oracle before moving to Eclipse Foundation (now Jakarta EE).
• Focused on:
o Cloud readiness
o Microservices architecture
o Modern web technologies (HTTP/2, JSON-B, JSF 2.3)
o Declarative security and Security API 1.0

Extra:
Key Technologies and Terms in Java EE 8
1. JSON-B (JSON Binding)
• Allows automatic conversion between Java objects and JSON.
• Based on JSON-P (Processing API) but offers higher-level APIs (like JAXB for XML).
Useful for RESTful services that exchange JSON data.

2. JAX-RS 2.1 (Java API for RESTful Services)


• Supports reactive clients, non-blocking I/O, and Server-Sent Events (SSE).
SSE: A technology that allows the server to push updates to the browser via HTTP.

3. CDI 2.0
• Adds asynchronous event support, better bootstrapping outside the Java EE container.
• Integrates tightly with other Java EE features (e.g., JSF, EJB, JAX-RS).

4. Java Servlet API (Updated for HTTP/2)


• Enhanced to support HTTP/2 features:
o Multiplexing: multiple requests over a single connection
o Server Push: pre-emptively sending data to clients
Servlets: Java classes that handle HTTP requests and generate dynamic web content.

5. Bean Validation 2.0


• Adds support for Java 8 features like lambda expressions and type annotations.
• Lets developers annotate fields and methods with constraints like @NotNull, @Email.

6. JSF 2.3 (JavaServer Faces)


• Component-based UI framework.
• Better support for AJAX, CDI integration, and Java SE 8 features.
AJAX: Enables asynchronous requests, so part of a page updates without reloading the whole page.

7. Java EE Security API 1.0

ADITI CHIKHALIKAR 9
• Simplifies security management with standardized APIs:
o User and role services
o Password aliasing
o Annotation-based authorization
Example: @RolesAllowed("ADMIN") to restrict access to methods.

8. Java EE Management API 2.0


• Introduced REST-based management interfaces.
• CRUD operations on managed objects, monitoring with SSE/WebSocket.
• Integrates deployment and configuration in one API.

9. MVC 1.0 (Model-View-Controller)


• An architecture pattern:
o Model: Business logic, uses CDI
o View: JSP or Facelets
o Controller: JAX-RS based classes
• Leverages existing EE technologies.

10. Java Messaging Service (JMS) 2.1


• Simplified asynchronous messaging between components.
• Better integration with Java EE transactions.
JMS: Enables sending/receiving messages between distributed systems (e.g., producer-consumer
pattern).

Transition to Microservices and Cloud


• Java EE 8 addressed the shift towards microservices, containerization, and cloud-native
architecture.
• APIs like JAX-RS, JSON-B, and CDI are ideal for building modular services.
• Foundation for the Jakarta EE platform under Eclipse.

Extra: Evolution of Enterprise Architecture


https://medium.com/razi-chaudhry/evolution-of-enterprise-architecture-ea-part-3-94beda636464

ADITI CHIKHALIKAR 10
7. What is Glassfish Server? Explain its Features in detail?
Answer:
• GlassFish is an open-source application server project started by Sun Microsystems for the
Java EE platform and now sponsored by Oracle Corporation.
• The supported version is called Oracle GlassFish Server.
• GlassFish is free software, dual-licensed under two free software licences: the Common
Development and Distribution License (CDDL) and the GNU General Public License (GPL)
with the classpath exception.
• GlassFish is the reference implementation of Java EE and as such supports Enterprise
JavaBeans, JPA, JavaServer Faces, JMS, RMI, JavaServer Pages, servlets, etc.
• This allows developers to create enterprise applications that are portable and scalable, and that
integrate with legacy technologies.
• GlassFish Server 4.0 Open Source Edition is a compatible, production implementation of Java
EE 7 platform specification built using an open source license.
• As with Java EE 5 and 6, the Reference Implementation of Java EE 7 is derived from Project
GlassFish.
• Administration:
• As an administrator of GlassFish Server, the main responsibilities are to establish a
secure GlassFish Server environment and to oversee the services, resources and users
that participate in that environment.

ADITI CHIKHALIKAR 11
• The key tasks include configuring resources and services, managing GlassFish Server
at runtime and fixing problems that are associated with the server, installing software
and integrating add-on components and deploying applications.
• Developers:
• For developers, GlassFish Server offers a lightweight runtime that starts in seconds
and enables rapid iterative development with Active Redeploy that saves session state
when an application is redeployed.
• Active Redeploy minimizes downtime by preserving session state and reloading only
necessary modules.
• IT Operations:
• For IT Operations, GlassFish Server offers a feature-rich web console for manual
operations and a feature-equivalent command line utility for automated environment.
• GlassFish Server 4.0 provides the following:
• A lightweight and extensible core based on OSGi Alliance standards
• A web container
• An easy-to-use Administration Console for configuration and management
• Update Tool connectivity for updates and add-on components
• Support for high availability clustering and load balancing

Extra:
Server Jakarta EE Lightweight Commercial Microservices
Support Support Friendly
GlassFish Moderate (community
only)
WildFly (use JBoss
EAP)
Payara Server (with Payara
Micro)
Apache (Web
TomEE Profile)
Open Liberty (see
WebSphere)
WebSphere
Liberty

ADITI CHIKHALIKAR 12
Chapter 2
8. Write a short note on Single tier architecture. OR Write a note on Single Tire EE
architecture along with its Advantages and Disadvantages.
Answer:
• Some applications are written to run on a single computer.
• All the services provided by the application i.e. the user interface, persistent data access and
the logic that processes the data input by the user and read and displayed to the user from a
data store, all exist on the same physical machine and are thus lumped [grouped] together
in the application.
• So in Single Tier Architecture
▪ The user interface of a Web application i.e. the presentation layer
▪ The middle ware i.e. the business rules
▪ The data access layer
▪ Are all contained in one single computer.
• Advantages:
▪ The simplest and least expensive alternative
▪ Less equipment to purchase and maintain
• Disadvantages:
▪ This type of implementation is lower security and the lack of scalability. An
architecture is scalable when it can be easily expanded or augmented to meet increasing
performance needs. Single Tier Architecture is not scalable.
▪ Having all of the site's major components and data on a single computer behind the
domain firewall leaves the site more vulnerable to malicious attacks
▪ Running all of the site's components on a single computer also limits expansion and
optimization possibilities
• If the developer knows that the application will not grow over time, then the developer may
decide to use single tier architecture.

9. Write a note on Two Tire EE application architecture. OR Explain two tier architecture
with its advantages and disadvantages.
Answer:
⮚ In this architecture, an application is divided into two components:
o Web Server
▪ Implements the user interface

ADITI CHIKHALIKAR 13
▪ Contains business logic
o Database Server
▪ Used to store and access business data, captured by the user interface run on
the Client in a data store at the Server
⮚ Hence in a two-tier architecture:
o The User Interface is always physically located in the user's desktop [i.e. the Client]
o The database management services are always physically located on a Server
⮚ The Server is always a more powerful machine as it has to service multiple client requests to
store or retrieve data.
⮚ The client machine gets the data from the user and passes it to the server for processing
whereas the server validates the input data based on business rule accordingly the data is
updated in the database.
⮚ Advantages:
o Adds additional security by removing sensitive customer data from the single
computer
o Having the database on a separate computer improves the overall performance of the
site
o Allows optimizing each machine for more specific performance requirements
⮚ Disadvantages:
o The increased cost and complexity of the architecture
⮚ While this is the recommended architecture for an initial electronic commerce site, provide a
cost benefit analysis to the customer to help them make the decision.

10. Write a short note on three tier architecture. OR Write a note on Three Tire EE architecture
along with its Advantages and Disadvantages.
Answer:
⮚ This architecture is the evolution of two tier applications. Logically the application is divided
into three constituent layers:
o User Services – Presentation Layer: Provides service such as the Graphical User
Interface and other automation tasks that the application has to perform
o Business Services - Business Layer: Implements business rules. This layer
encapsulates the business logic from users such that they need not know how business
logic is applied When business is upgraded, only the business layer is affected and
must be upgraded. the rest of the application services can remain untouched.

ADITI CHIKHALIKAR 14
o Data Services - Data Layer: Provides data availability and integrity. It is responsible
for adding, modifying and deleting data from the data store
⮚ This architecture, while it is the most expensive, is the most secure and scalable of the three
options.
⮚ Since, the Business Layer has been moved from the Presentation Layer, it reduces the security
risk.
⮚ As usage on the site grows, additional Business Layer can be added and the application can
be cloned across multiple computers.
⮚ Advantages of Three-Tier Architecture:
o Modular Development: Each layer is independent and can be developed and updated
separately.
o Improved Security: Business logic is separated from the presentation layer, reducing
exposure.
o High Scalability: Business layers can be replicated across servers to handle more
load.
o Better Maintainability: Updates or fixes in one layer do not affect others.
o Each of the three layers can be optimized for peak performance:
▪ Presentation Layer focuses on network I/O (input/output between user and
server)
▪ Business Layer is CPU-intensive, performing all logical computations
▪ Data Layer is disk I/O intensive, handling database read/write operations
⮚ Disadvantages of Three-Tier Architecture:
o Higher Cost: More complex and expensive to design, develop, and maintain.
o Increased Latency: Due to the separation of layers, communication between layers
may introduce delays.
o Complex Deployment: Managing and configuring all three tiers requires more
technical effort.
o Requires Skilled Developers: Knowledge of multi-tiered system architecture is
necessary.

11. What is need of multi‐tier architecture and explain its functionality. OR Write a note on
Multi Tire EE architecture along with its Advantages and Disadvantages.
Answer:

ADITI CHIKHALIKAR 15
⮚ Java EE architecture is based on the notion of Multi-tier applications. Java EE makes it easy to
build industrial-strength applications based on two, three or more application layer and provides
all that is required to make this possible.
⮚ Multi-tier architecture doesn’t replace two-tier or three-tier models — in fact, it can include
them depending on the needs of the application.
⮚ For small or department-specific applications, two-tier or three-tier architecture is often
sufficient.
⮚ The application logic is Basically divided by its functionality:
o User Interface Tier: Interface the user interacts with (web browser, desktop app, or
mobile device).
o Presentation Tier:
▪ Controls how user data is displayed and how requests are handled.
▪ May differ slightly for different client types (web, mobile, etc.).
o Business Tier:
▪ The core logic of the application.
▪ Contains business rules and processes.
▪ It doesn't deal with UI, databases, or formatting—only decision-making logic.
▪ Example: Minimum wage check in a payroll system.
o Infrastructure Services: Provides essential services like messaging, security, and
transaction support.
o Integration Tier / Data Access Tier:
▪ Manages access to external systems and relational databases.
▪ Doesn’t apply business rules—just connects to data sources.
o Data Tier:
▪ Stores and retrieves actual business data.
▪ Typically consists of relational databases (Oracle, MySQL), text files, etc.
▪ It does not decide how the data is used—only handles storage.
⮚ Advantages of Multi-Tier Architecture:
o Separation of Concerns: Each layer handles a specific task, making development and
maintenance easier.
o Scalability: Layers like the business or data tier can be scaled independently to handle
increased load.
o Flexibility: You can easily replace or upgrade one tier without affecting others.
o Security: Sensitive logic is kept away from the user interface, reducing security risks.
o Reusability: Common services (like data access or messaging) can be reused by multiple
applications.
⮚ Disadvantages of Multi-Tier Architecture:
o Increased Complexity: More layers mean more components to manage and configure.
o Higher Cost: Development and maintenance costs can be higher due to added architectural
overhead.
o Slower Performance: More communication between layers can introduce latency.
o Requires Skilled Developers: More architectural understanding is needed to implement
and maintain properly.

ADITI CHIKHALIKAR 16
12. Explain the architecture of Java Enterprise Application.
Answer:
⮚ Enterprise Application is a business application.
⮚ In today’s corporate environment, enterprise applications are complex, scalable, distributed,
component-based, and mission-critical.
⮚ They may be deployed on a variety of platforms across corporate networks, intranets, or
the Internet.
⮚ A distributed, multi-tiered, application model can be described as an enterprise
application.
⮚ Application logic is divided into components according to functions and various application
components put together to make up the enterprise application.
⮚ These components are physically installed on different computers, at different physical
locations, depending on the tier in the multi tiered environment to which application
component belongs.
Architecture of Enterprise Application
❑ Enterprise architecture is divided into the following tiers:
⮚ Client Tier Services run on the client machine.
⮚ Web Tier Services run on the server.
⮚ Business Tier Services run on the server.

ADITI CHIKHALIKAR 17
⮚ Enterprise Information System[EIS] Tier Services run on the EIS server.
❑ The tiers can be further divided into layers, which provide granular level functions.
Client Tier ( On Client Machine)
Application Client Dynamic HTML Pages

Web Tier (On Java EE Server)


Servlets Java Beans JSP JSTL JSF

Business Tier (On Java EE Server)


Enterprise Java Bean Enterprise Java Bean

EIS Tier (Database Server Machine)


Database Database Database

❑ The Client Tier


⮚ Consists of a client program that makes requests to the Web Tier.
⮚ The client can be:
• Dynamic HTML Pages
• An Application client
➢ Dynamic HTML Pages
⮚ Consists of:
⮚ Dynamic web pages containing various types of markup language such as HTML,
XML, etc. which are generated by web components running in the web tier.
⮚ A web browser, which renders the pages received from the server.
⮚ Do not: query databases, execute complex business rules, connect to legacy
applications.
⮚ Application Client
⮚ Runs on client machine.
⮚ Provides a richer user interface than cannot be provided by a markup language.
⮚ Has GUI created from Swing or AWT API.
⮚ Can open an HTTP connection to establish communication with a Servlet running in
the web tier.
⮚ Application Client written in languages other than Java can interact with Java EE
servers, enabling the Java platform to interoperate with legacy systems, clients and
non-Java languages.

❑ The Web Tier


⮚ Consists of components that handle interaction between clients and business tier.
⮚ Performs:

ADITI CHIKHALIKAR 18
⮚ Dynamically generate content in various formats for the client.
⮚ Collect input from the client and return appropriate results from components
❑ Business Tier.
⮚ Control the flow of screens or pages on the client.
⮚ Maintain state of data for a user’s session.
⮚ Perform basic logic and hold data temporarily.
⮚ Following Java EE technologies are used in Web Tier:
⮚ Servlets
⮚ JavaServer Pages[JSP]
⮚ JavaServer Faces[JSF]
⮚ JavaServer Faces Facelets
⮚ Expression Language
⮚ JavaServer Pages Standard Tag Library[JSTL]
⮚ JavaBeans Components

❑ The Business Tier


⮚ Consists of components that provide the business logic for an application.
⮚ Code that provides functionality to a particular business domain such as banking,
retail, finance or an e-commerce site.
⮚ The business logic is handled by Enterprise Beans.
⮚ Following Java EE technologies are used in business Tier:
⮚ Enterprise JavaBeans[EJB]
⮚ Java Persistence API[JPA]
⮚ An enterprise bean:
❑ Receives data from the client program.
❑ Processes it, of necessary
❑ Sends it to the Enterprise Information System Tier for storage
❑ Retrieves data from Storage
❑ Processes it, if necessary.
❑ Sends it back to the client program.
❑ The Enterprise Information System[EIS] Tier
⮚ Consists of:
❑ Database Servers
❑ Enterprise Resource Planning Systems
❑ Mainframe Transaction Processing
❑ Other legacy information systems
⮚ Resources located on a separate machine than the EE server and accessed by
components on the Business Tier.
⮚ Following Java EE technologies are used in EIS Tier:
❑ Java Database Connectivity[JDBC]
❑ Java Persistence API[JPA]
❑ Java EE Connector Architecture
❑ Java Transaction API[JTA]

ADITI CHIKHALIKAR 19
❑ Java EE Server
o Is a server application that implements the Java EE platform APIs and provides the
standard Java EE services. Sometimes called Application Servers.
o Host several application component types that correspond to the tiers in a multi-tiered
application.
o During the deployment process, installation of Java EE application takes place in the
Java EE Containers on the Java EE Server.
o Java EE Server is used as runtime portion for the execution of application, which
contains the EJB and Web Containers.

13. Explain different types of System architecture of JavaEE6?


Answer:
Give Explanation of Single tire, 2 tire, 3 tire, Multi-tire Architecture and Enterprise Architecture.

14. What are the various factors important before deciding on the number of tiers in application
architecture?
Answer:
As a developer, before deciding on the number of tiers in application architecture, the following
factors must be considered:
• Scalability: The capability of an application to adapt to any new hardware environment
• Availability: The ability of an application to cater to the increased demands from clients
• Extensibility: The ability of an application to incrementally add features from time to
provide better functionality to the client time to improve performance and
• Maintainability: The ability of an application to respond to bug-fixes with the minimum
utilization of resources in terms of people, time and technology
• Security: The ability of an application to maintain the integrity of data
• Performance: The ability of an application to respond to a client request in the minimum
time.

15. What are Java EE containers?


Answer:
Java EE Containers:
• Java EE containers are a fundamental part of the Java EE architecture that provide the
runtime environment for Java EE application components (such as Servlets, JSPs, EJBs,
etc.).
• They serve as an interface between the application components and the low-level
platform-specific infrastructure of the Java EE server.
• Before execution, components like web modules, enterprise beans, or application clients
must be packaged into Java EE modules and deployed into their respective containers.
• Java EE containers handle the lifecycle management, security, transactions, and resource
management for the deployed components.
• The following are the services provided by container to a component:
o Allows configuring a web component or enterprise bean so that only authorized users
can access the system resources
o Allows specifying relationships among methods that make up a single transaction so
that all methods in one transaction are treated as a single unit
o Provides a unified interface to multiple naming and directory services in the enterprise
so that application components can access these services

ADITI CHIKHALIKAR 20
o Manage low-level communications between clients and enterprise beans. After an
enterprise bean is created, a client invokes methods on it as if it were in the same
virtual machine
• The container also manages non-configurable services such as enterprise bean and Servlet
lifecycles, database connection resource pooling, data persistence and access to the Java EE
platform APIs.

16. Explain different type of containers. OR Classify the EE Containers. Explain. OR Define
Java EE containers with various Java Container types.
Answer:

• Containers are the interface between a component and the low-level platform-specific
functionality that supports the component.
• Before a web, enterprise bean, or application client component can be executed, it must be
assembled into a Java EE module and deployed into its container.
Different Container Types:
• Enterprise JavaBean (EJB) Container:
▪ Provides the runtime environment for Enterprise Beans.
▪ Supports modular development of business logic in enterprise applications.
▪ Manages:
• Lifecycle of EJBs.
• Transaction handling.
• Security.
• Remote/local access.
▪ Types of EJBs:
• Session Beans – Represent transient tasks, usually accessed by one client.
• Entity Beans – Represent persistent data (typically database records).
• Message-Driven Beans – Handle asynchronous messaging.
• Web Container:
o The web container provides the runtime environment required for web
components such as Servlets and JSPs (JavaServer Pages).
o It is responsible for managing the execution of these components in a Java EE
application.
o The web container offers following services for servlets and jsp: including lifecycle
management, security, and communication support.
o Both the web components and the web container run on the Java EE server,
enabling the delivery of dynamic web content.
o The web server is designed to handle HTTP requests sent by clients and respond
with appropriate HTTP responses, forming the backbone of web-based
communication.
• Application Client Container:
o To host application components, application clients, the application client container is
used.
o It runs on the client computer and it can be interacted with each other.
o It helps developers to create robust Java applications that also have access to Java EE
resources such as data sources or EJBs.
o This container manages the execution of application client components. Application
clients and their container run on the client.
o Application server can handle all application operations between users and databases

ADITI CHIKHALIKAR 21
• Applet Container:
o Applet container includes support for the applet programming model.
o The applet container is a mixture of web browser and java plug in on client machine.
o The applet container uses the sandbox security model, preventing applets from
accessing system resources and causing harm.
o Applet container ensures security and portability if it runs in an applet.

17. What are the services provided by Java EE server and Java EE Container?
Answer:
Java EE Server
• Is a server application that implements the Java EE platform APIs and provides the standard
Java EE services.
• Sometimes called Application Servers because they allow serving application data to clients,
much as how Web Servers serve web pages to Web Browsers.
• Host several application component types that correspond to the tiers in a multi-tiered
application.
• During the deployment process, installation of Java EE application takes place in the Java
EE Containers on the Java EE Server.
• Java EE Server is used as runtime portion for the execution of application, which contains
the EJB and Web Containers.
Java EE Container
• Java EE application components use the protocols and methods of the container to access
other application components and services provided by the Java EE server. The Java EE
application server provides an application client container, an applet container, a web
container and an EJB container.
• The following are the services provided by container to a component:
o Allows configuring a web component or enterprise bean so that only authorized users
can access the system resources
o Allows specifying relationships among methods that make up a single transaction so
that all methods in one transaction are treated as a single unit
o Provides a unified interface to multiple naming and directory services in the enterprise
so that application components can access these services
o Manage low-level communications between clients and enterprise beans. After an
enterprise bean is created, a client invokes methods on it as if it were in the same
virtual machine
• The container also manages non-configurable services such as enterprise bean and Servlet
lifecycles, database connection resource pooling, data persistence and access to the Java EE
platform APIs.

ADITI CHIKHALIKAR 22
Chapter 3
18. What is Static Content?
Answer:
Static Web Sites
• If the contents of a Web Site are not changeable over the period, then website is called as
Static Website.
• The content of static Web sites is difficult to modify because it includes bulk of the content
like text, graphic, and multimedia; content is usually stored in HTML pages and not in
databases.
• Static Web pages are very simple in layout and informative in context.
• The basic disadvantage of static web sites is the web pages are developed at the time of
constructing the site. All static website owners are dependent on Web professionals whenever
any changes become necessary. The initial cost of developing static Website may not be costly
but its long-term maintenance will be expensive.
• Application areas of Static Website / Need of Static web pages arise in the following cases?
• Changes to web content are not on regular basis.
• Simple Email based ordering system should be adequate No advanced online ordering
facility is required
• Features like order tracking, verifying availability of stock, online credit card transactions,
are not needed.
• Web site not required to be connected to back-end system.
• List of inventory and services offered are limited.

19. Explain need of dynamic contents.


Answer:
• Website is collection of web pages of similar content and type. Websites are categorized in
two categories as Static Web Sites & Dynamic Web Sites.
• In the earlier days, web pages were static i.e., a user requests a resource (such as video, image,
web page, etc.) and the server returns it.
• If the contents of the website are regularly subject to change, then this kind of website is
known as Dynamic website.
• If the contents of a Web Site are not changeable over the period, then website is called as
Static Website.
• The content of static Web sites is difficult to modify because it includes bulk of the content
like text, graphic, and multimedia; content is usually stored in HTML pages and not in
databases.
• Static Web pages are very simple in layout and informative in context.
• The Dynamic websites has the unique advantage of not having to hazardously depend on Web
professionals for effecting modification to the Website.
• Dynamic-content Web site can be maintained directly by the site owner. The initial
development cost of Dynamic-content Web sites is high but there will be massive saving in
succeeding maintenance costs. The owners will not be required to pay Web professionals
every time a change in the Web content is needed.
• A dynamic website design will become necessary for online databases, e-businesses, and
online shopping sites. A dynamic web design page has the facility to change content by a
program.

ADITI CHIKHALIKAR 23
• However, with the growth of commercial activities on the Web and the rapid spread and
adoption of the World Wide Web as a network without geographical boundaries, companies
wanted to deliver dynamic contents to their clients such as:
o Displaying Bank Account Details.
o Performing online banking transactions.
o Tracking and offering modified services to clients.
o When need for more complicated ordering system with a wide variety of functions.
o Booking tickets.
o Weather reports.
o News headlines.

20. Explain CGI technology and what are its disadvantages?


Answer:
⮚ The common gateway interface (CGI) is a standard way for a Web server to pass a Web user's
request to an application program and to receive data back to forward to the user.
⮚ When the user requests a Web page (for example, by clicking on a highlighted word or
entering a Web site address), the server sends back the requested page.
⮚ However, when a user fills out a form on a Web page and sends it in, it usually needs to be
processed by an application program.
⮚ The Web server typically passes the form information to a small application program that
processes the data and may send back a confirmation message.
⮚ The method or convention for passing data back and forth between the server and the
application is called the common gateway interface (CGI). It is part of the Web's Hypertext
Transfer Protocol (HTTP).
⮚ The Common Gateway Interface (CGI), was one of the practical technique developed for
creating dynamic content.
⮚ A CGI program can be written in many languages such as C, C++, VB Script, Python,
PERL.
⮚ By using the CGI, a web server passes requests to an external program and after executing the
program the content is sent to the client as the output.
⮚ Disadvantages of Common Gateway Interface (CGI)
o Platform dependent
o A process thread consumes a lot of server-side resources especially in multi user
situation.
o Difficult for beginners to program modules in this environment.
o Sharing resources such as database connections between scripts or multiple calls to
the same script was not available, leading to repeated execution of expensive
operations.
o Lack of Scalability and reduced speed- Each time a request is received by the web
server, an entirely new process is created.
o Some Alternatives: FastCGI, mod-perl, NSAPI, ISAPI, Java Servlets.
o Most of these technologies have better performance as compared to CGI, But Java
Servlets have actually replaced CGI.

ADITI CHIKHALIKAR 24
21. What are alternatives to CGI? Explain in Detail.
Answer:

To overcome the disadvantages of CGI, various other technologies or framework were introduced:

1. ASP Active Server Pages, or ASP, was created by Microsoft for its web server, but it is now
available for many servers. The ASP engine is integrated into the web server so it does not ire an
additional pro ess. It allows programmers to mix code within HTML pages instead of writing separate
programs.

2. PHP: PHP is a programming language that is similar to Perl, and its interpreter is embedded within
the web server. PHP supports embedded code within HTML pages. PHP is supported by the Apache
web server.

3. ColdFusion: Allaire's ColdFusion creates more of a distinction than PHP between code pages and
HTML pages. HTML pages can include additional tags that call ColdFusion functions. A number of
standard functions are available with create their own controls as extensions. ColdFusion, and
developers can ColdFusion was originally written for Windows, but versions for various Unix
platforms are now available as well.

4. Java servlets : Java servlets were created by Sun. Servlets are similar to CGI scripts in that they are
code that creates documents. However, servlets, because they use Java, must be compiled as classes
before they are run, and servlets are dynamically loaded as classes by the web server when they are
run. JSP is another technology that allows developers to embed Java in web pages, much like ASP.

5. FastCGI: FastCGI maintains one or more instances of PERL that it runs continuously along with
an interface that allows dynamic requests to be passed from the web server to these instances. It avoids
the biggest drawback to CGI, which is creating a new process for each request, while still remaining
largely compatible with CGI. FastCGI is available for a variety of web servers.

6. mod_perl: mod_perl is a module for the Apache web server that also avoids creating separate
instances of perl for each CGI. Instead of maintaining a separate instance of perl like FastCGI,
mod_perl embeds the perl interpreter inside the web server.

ADITI CHIKHALIKAR 25
22. How is Servlet better than CGI?
Answer: same as below write point by point.
23. Servlet Vs CGI
Answer:
CGI (Common Gateway Interface) Servlet
CGI is Written in C, C++, PERL, Visual Basic Servlets are Written in Java
CGI is Platform specific, application specific Servlets are Platform Independent
CGI is Not Portable Servlets are Portable
CGI is Difficult to maintain, non-scalable, non- Servlets are Powerful, reliable, and efficient
manageable
CGI is Prone to security problems of Servlets use built-in security of Java, hence
programming Languages more secure
In CGI each request is handled by heavy weight In Servlets each request is handled by
OS Process lightweight Java Thread
In CGI data sharing is not available. In Servlets, data sharing is possible.
CGI does not link the web server directly to the Servlet can link directly to the web server.
server.
CGI is not able to read the HTTP servers.Servlets are useful to read and set the
HTTP servers.
CGI is slower Servlet is faster
Session tracking and caching of previous Session tracking and caching of previous
computations cannot be performed. computations is possible.

24. What is Servlet and Why Servlets and What can Servlets do? OR List the tasks that Servlet
can do? OR describe the Servlet Architecture- Request/ Response. OR List the tasks that
Servlet can do?
Answer:
⮚ A Servlet is a small , self-contained, portion of code that is executed at web server in response
to an HTTP request from a clients browser.
⮚ Servlets can do following things:
o A Servlet can process or store data submitted by an HTML form.
o A Servlet can provide dynamic content, eg: return the results of a database query to
the client.
o A Servlet can manage state information on stateless HTTP, eg: for an online shopping
cart system which manages shopping carts for many concurrent customers and maps
every request to the right customer.
o A Servlet can handle multiple request concurrently.
o Servlets can forward request to another servers and Servlet. This allows them to be
used to balance load among several servers that mirror the same content.
o A Servlets can maintain and track sessions.
o Servlets can pass data between themselves
o Servlets allow you to access the EJBs.
⮚ Servlet Architecture– Request/Response
o A web browser sends a request to the Web server for HTML page.
o The Web server forwards this request to a Servlet.
o The Servlet processes the request, construct an appropriate response and returns the
response to the requesting Web browser via the Web server.
⮚ The following figure depicts a typical servlet life-cycle scenario.

ADITI CHIKHALIKAR 26
o The HTTP requests coming to the server are delegated to the Servlet container.
o The Servlet container loads the Servlet before invoking the service() method.
o Then the Servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.

Why Servlets:
⮚ Are loaded into memory once and run from memory thereafter.
⮚ Are spawned as a thread, not a process.
⮚ Are a powerful object-oriented abstraction of HTTP.
⮚ Are portable across multiple Web servers and platforms.
⮚ Are simple to design and implement.
⮚ Are tightly integrated with the web server.
⮚ Service client request very efficiently.
⮚ Runs within secure and reliable scope of JVM.
⮚ Are scalable, robust, secure CGI replacement.
⮚ Are supported by several Web Servers.
⮚ Being on the server-side provides code protection.
⮚ Provide direct DB access using native and ODBC based DB drivers.

ADITI CHIKHALIKAR 27
Chapter 4

25. Explain servlet skeleton.


Take from Practical 1 A.

26. Explain the life cycle of a servlet. OR Explain servlet life cycle with diagram? U What are
the life cycle methods of Servlet? Describe with suitable diagram. OR Explain Working of
Servlet with help of Suitable diagram?
Answer:

ADITI CHIKHALIKAR 28
● The Servlet lifecycle describes how a Servlet is:
1. Loaded.
2. Instantiated.
3. Initialized.
4. Services requests.
5. Destroyed.
6. Finally garbage collected.
❑ Initialization
▪ In order to initialize a servlet, the Servlet engine first locates its class. A Servlet
class may reside on the local file system, a remote file system or be some other
network.
▪ Once loaded, the servlet engine instantiates an instance of the Servlet class.
▪ Then it calls the Servlet’s init() method.
▪ init():
public void init(ServletConfig config) throws ServletException
▪ In entire lifecycle of servlet init() is called only once.
❑ Runtime
▪ After the server loads and initializes the servlet, the servlet is able to handle clients
requests. It processes them in service().
▪ Each client’s request to service() is run in separate Servlet thread.
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
▪ ServletRequest object helps in accessing the original request data & ServletResponse
object provides methods that helps the Servlet to build a response.
⮚ Destruction
▪ When instructed to unload the servlet, perhaps by the server administrator or
programmatically by the servlet itself, the servlet engine calls the servlet’s destroy().
The servlet is then eligible for garbage collection.
▪ All resources which are allocated in init() should be released in destroy()
public void destroy().
▪ The method is run only once.
▪ The common tasks implemented in destroy() are:
▪ Synchronizing cleanup tasks such as closing any open resources, closing a connection pool.
▪ Informing another application that servlet will no longer be in service.

27. Explain the life cycle of a servlet application. OR Write a note of life cycle methods of servlet.
Answer:
The life cycle of a Servlet is managed by the container in which the Servlet has been deployed. When
a request is mapped to a Servlet, the container performs the following steps.
1) If an occurrence of the Servlet does not exist, the Web container …
● Loads the Servlet class.
● Creates an instance of the Servlet class.
● Initializes the Servlet instance by calling the init method. Initialization is covered in Initializing a
Servlet.

2) Invokes the service method, passing a request and response object. Service methods are discussed
in the section Writing Service Methods.

ADITI CHIKHALIKAR 29
If the container needs to remove the Servlet, it finalizes the Servlet by calling the Servlets destroy
method.
The following are the life cycle methods of a Servlet instance:

1: init( ) : This method is called once for a Servlet instance. When first time Servlet is called, Servlet
container creates instance of that Servlet and loaded into the memory. Future requests will be served
by the same instance without creating the new instance. init( ) method is used for inilializing Servlet
variables which are required to be passed from the deployment descriptor web.xml. The ServletConfig
is passed as the parameter to init( ) method which stores all the values configured in the web.xml.

public void init(ServletConfig config) throws ServletException

2: service( ): This method is called for the each request. This is the entry point for the every Servlet
request and here we have to write our business logic or any other processes. This method takes
HttpServletRequest and HttpServletresponse as the parameters.

public void service(ServletRequest request, ServletResponse response) throws


ServletException, IOException

3: destroy( ): This method will be called once for an instance. It is used for releasing any resources
used by the Servlet instance. Most of the times it could be database connections, File I/O operations,
etc. destroy( ) is called by the container when it is removing the instance from the Servlet container.

public void destroy().


▪ The method is run only once.
▪ The common tasks implemented in destroy() are:
▪ Synchronizing cleanup tasks such as closing any open resources, closing a connection pool.
▪ Informing another application that servlet will no longer be in service.

ADITI CHIKHALIKAR 30
28. Write a short note on Java servlet API.
Answer:
⮚ Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http: they constitute the Servlet API.
⮚ These packages are not part of the Java core packages. Instead, they are standard extensions
provided by Tomcat.
⮚ The Servlet API has been in a process of ongoing development and enhancement. The current
servlet specification is version 3.0.

❑ The javax.servlet Package


⮚ The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
⮚ Defines methods that all servlets must implement. Servlets receive and respond to requests
from Web clients, usually across HTTP, the HyperText Transfer Protocol.
⮚ To implement this interface, you can write a generic servlet that extends
javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
⮚ This interface defines methods to initialize a servlet, to service requests, and to remove a
servlet from the server. These are known as life-cycle methods and are called in the following
sequence:
⮚ 1. The servlet is constructed, then initialized with the init( ) method.
⮚ 2. Any calls from clients to the service method are handled.
⮚ 3. The servlet is taken out of service, then destroyed with the destroy method, then garbage
collected and finalized.

ADITI CHIKHALIKAR 31
⮚ The following table summarizes the core interfaces that are provided in this package. The
most significant of these is Servlet.
⮚ All servlets must implement this interface or extend a class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.

❑ The javax.servlet.http Package


⮚ The javax.servlet.http package contains a number of classes and interfaces that describe and
define the contracts between a servlet class running under the HTTP protocol and the runtime
environment provided for an instance of such a class by a conforming servlet container.
⮚ The following table summarizes the core interfaces that are provided in this package. The
most significant of these is HttpServlet.
Interface Description

HttpServletRequest Extends the ServletRequest interface to provide request information


for HTTP servlets.
HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific
functionality in sending a response.
HttpSession Provides a way to identify a user across more than one page request
or visit to a Web site and to store information about that user.
HttpSessionBindingListener Causes an object to be notified when it is bound to or unbound from
a session.
Part This class represents a part or form item that was received within
a multipart/form-data POST request.
WebConnection This interface encapsulates the connection for an upgrade request.

ADITI CHIKHALIKAR 32
Class Description

Cookie Creates a cookie, a small amount of information sent by a servlet


to a Web browser, saved by the browser, and later sent back to
the server.
HttpServlet Provides an abstract class to be subclassed to create an HTTP
servlet suitable for a Web site.
HttpSessionBindingEvent Events of this type are either sent to an object that
implements HttpSessionBindingListener when it is bound or
unbound from a session, or to a HttpSessionAttributeListener that
has been configured in the deployment descriptor when any
attribute is bound, unbound or replaced in a session.

• The GenericServlet class provides implementations of the basic life cycle methods for a
servlet.
• GenericServlet implements the Servlet and ServletConfig interfaces. In addition, a method
to append a string to the server log file is available. The signatures of this method are shown
here:
void log(String s)
void log(String s, Throwable e)
• Here, s is the string to be appended to the log, and e is an exception that occurred
29. Write note on javax.servlet package and Servlet config.
Answer:
⮚ The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
⮚ Defines methods that all servlets must implement. Servlets receive and respond to requests
from Web clients, usually across HTTP, the HyperText Transfer Protocol.

ADITI CHIKHALIKAR 33
⮚ The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.
The methods declared by this interface are summarized here:

30. Write a short note on Servlet interface and explain its methods.
• All servlets must implement the Servlet interface. It declares the init( ), service( ), and
destroy( ) methods that are called by the server during the life cycle of a servlet.
• A method is also provided that allows a servlet to obtain any initialization parameters.
• The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These
are invoked by the server.
• The getServletConfig( ) method is called by the servlet to obtain initialization parameters.
• A servlet developer overrides the getServletInfo( ) method to provide a string with useful
information (for example, author, version, date, copyright). This method is also invoked by
the server.
• Provides following functionalities:
▪ Initializing a Servlet
▪ Handling a client request
▪ Destroying a servlet

ADITI CHIKHALIKAR 34
31. Write short note on ServletContext interface.

32. Explain ServletRequest and ServletResponse interface.


Answer:
⮚ The ServletRequest interface enables a servlet to obtain information about a client request.
⮚ It encapsulates the communication from the client to the server.
⮚ ServletRequest interface allows the Servlet to access information such as:
⮚ Name of the parameters passed by the client.
⮚ The protocol[scheme] such as HTTP POST and PUT methods being used by the
client.
⮚ The names of the remote host that made the request.

ADITI CHIKHALIKAR 35
⮚ The server that received it.
⮚ An input stream for reading the binary data from the request body.
⮚ Several of its methods are summarized in Table 31-3.

⮚ The ServletResponse interface enables a servlet to formulate a response for a client.


⮚ ServletResponse interface allows Servet:
● To set the content length and mime type of the reply.
● Provides a OutputStream and a reader.

33. Write short note on Part and WebConnection interfaces.

Part Interface (javax.servlet.http.Part)


The Part interface was introduced in Servlet 3.0 to provide built-in support for file uploads via
multipart/form-data requests (commonly used in HTML forms with file input fields).
Multiple Parts: request.getParts() returns a Collection<Part> for processing all parts.
Annotations: Works with @MultipartConfig on servlets to enable upload.
Feature Description
getName() Returns the name of the form field.
getSubmittedFileName() Returns the original filename uploaded by the client.
getSize() Returns the size (in bytes) of the uploaded part.
getContentType() Returns MIME type (e.g., image/jpeg, application/pdf).
getInputStream() Provides InputStream to read binary file data.
write(String) Saves the file on disk at the specified location.
delete() Deletes temporary data associated with the part.

ADITI CHIKHALIKAR 36
B. WebConnection Interface (Non-standard / server-specific)
The WebConnection interface is not part of the official Servlet API, but may exist in custom
implementations (e.g., JBoss Web, Undertow, or internal frameworks). It typically deals with low-
level socket communication between client and server.
• Non-standard Interface: WebConnection is not part of the official Java Servlet API; it is
used in specific web servers or frameworks (e.g., JBoss, Undertow).
• Low-Level HTTP Access: It provides direct access to the underlying client-server
connection, including raw input/output streams.
• Internal Use: Typically used internally by servlet containers for managing socket
connections, asynchronous I/O, or protocol upgrades like WebSocket.
• Supports Advanced Features: Useful in implementing non-blocking I/O, reactive
programming, or custom protocols outside the traditional servlet model.
• No Portability: Since it is server-specific, code using WebConnection will not work across
all servlet containers (e.g., Tomcat doesn’t support it).
• No Standard Documentation: It lacks official Java EE/Jakarta EE documentation and
varies across implementations.
• Not for General Developers: It is not intended for typical servlet developers; use it only
if you're building a container or low-level server module.

34.Write a note on HTTPServlet.


Answer:
HttpServlet Class:
⮚ The HttpServlet class extends GenericServlet. It is commonly used when
developing servlets that receive and process HTTP requests.
⮚ The methods of the HttpServlet class are:

ADITI CHIKHALIKAR 37
35.Explain HttpServletRequest Interface and HttpServletResponse Interface.
Answer:
⮚ The HttpServletRequest interface enables a servlet to obtain information about
a client request.
⮚ It provides methods for extracting HTTP parameters from the query string or
the request body depending on the type of request such as GET or POST.
Several of its methods are:

⮚ The HttpServletResponse interface enables a servlet to formulate an HTTP


response to a client. Several constants are defined. These correspond to the
different status codes that can be assigned to an HTTP response. For example,
SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND
indicates that the requested resource is not available.
⮚ HttpServletResponse interface provides an OutputStream for returning
binary data such as GIF or JPEG image and PrintWriter for returning text
output.
⮚ Several methods of this interface are :

ADITI CHIKHALIKAR 38
36.Write a note on HTTP Session Interface.
Answer:
⮚ HttpSession Interface provides a way to identify a user across more than one
page request or visit to a website and to store information about that user.
⮚ With the help of the HttpSession interface, a session can be created between
an HTTP client and an HTTP server. This session can persist for a specified
time period, across more than one connection or page request from the user.
⮚ This interface allows Servlets to:
❑ View and manipulate information about a session such as:
● The session identifier
● Creation time
● Last accessed time
❑ Bind objects to sessions, allowing user information to persist across multiple
user connections.
⮚ A servlet obtains an HttpSession object using getSession() of
HttpServletRequest.

ADITI CHIKHALIKAR 39
37.Write a note on Cookie Class.
Answer:
⮚ Used for Session management or where it is required to uniquely identify a
client.
⮚ Servlet uses getCookies() of HTTPServletRequest to retrieve cookies
submitted as part of client request.
⮚ addCookie() of HttpServletResponse can be used to send a new cookie to the
Web browser.
⮚ Cookie class allows Servlets to:
⮚ Read, create and manipulate HTTP-style cookies
⮚ Store small amounts of data on the client.

ADITI CHIKHALIKAR 40
Chapter 5
38. Explain Deployment descriptor file with its elements. U
Answer:
Deployment descriptor file and its elements
• Servlet API version 3.0 onwards, the deployment descriptor [web.xml] takes precedence over
annotations. [Contents in deployment descriptor will be followed even if annotations are
present.]
• The deployment descriptor overrides configuration information specified through the
annotation mechanism.
• Version 3.0 of the web deployment descriptor contains a new attribute called metadata-
complete on <web-app>.
• This attribute defines whether the web descriptor is complete or whether the class files of the
web application should be examined for annotations that specify deployment information.
• If this attribute is set to true, the deployment tool must ignore any servlet annotations present
in the class files and use only the configuration details mentioned in the descriptor.
• Otherwise, if the value is not specified [default is false] or set to false, the container must scan
all class files of the application for annotations.
• This provides a way to enable or disable scanning of the annotation and its processing during
the startup of the application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>SimpleCal</servlet-name>
<servlet-class> demoCal.SimpleCal </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleCal </servlet- name>
<url-pattern>/SimpleCal</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout> 30 </session-timeout>
</session-config>
</web-app>

• <web-app> Element
o All the entries are wrapped within a pair of opening and closing <web-app> elements.
o The body of <web-app> itself contains additional elements that determine how the
Web application will run in the GlassFish Server.
• <servlet> Element
o Servlets are registered and configured as a part of Web application. To register a
Servlet, add several entries to the Web Application deployment descriptor.
o <servlet>
--------
</servlet>
o <servlet> holds the declarative data of a servlet.
• <servlet-name> Element
o To deploy a Servlet, give the Servlet a name, specify the class file or the JSP' file used
to implement its behavior and set other Servlet-specific properties.

ADITI CHIKHALIKAR 41
o <servlet-name>WelcomeServlet</servlet-name>
o <servlet-name> defines the canonical name of the Servlet used to reference the Servlet
definition elsewhere in the deployment descriptor.
• <servlet-class> Element
o <servlet-class>servlet.WelcomeServlet</servlet-class>
o <servlet-class> is the fully-qualified class name of the Servlet.
• <servlet-mapping> Element
o <servlet-mapping>
--------
--------
</servlet-mapping>
o <servlet-mapping> defines a mapping between a Servlet and a URL. pattern.
• <servlet-name> Element
o <servlet-name>WelcomeServlet</servlet-name>
o <servlet-name> is the name of the Servlet to which the URL pattern is being mapped
to. This name corresponds to the name assigned to a Servlet in <servlet> declaration
element.
• <url-pattern> Element
o <url-pattern>/WelcomeServlet</url-pattern>
o <url-pattern> describes a pattern used to resolve URLs. The portion of the URL after
http://host:port + WebAppName is compared to the url-pattern by Web Server.
o If the patterns match, the Servlet mapped in this element will be called.
o In the above example, <servlet-mapping> informs the Web server that if it receives
any URI that matches the pattern/SimpleCal then it should pass the request to the
Servlet with the name SimpleCal.
• <session-config> Element
o <session-config>
---------
</session-config>
o To configure the session information, use <session-config>.
• <session-timeout> Element
o <session-timeout>30</session-timeout>
o <session-timeout> defines the timeout for a session in minutes.
• <welcome-file-list> Element
o <welcome-file-list>
----------
</welcome-file-list>
o A list of filenames that the server should try when the user accesses a path that
represents a WAR subdirectory [that is not already explicitly mapped to a Servlet] is
specified using <welcome-file-list>.
• <welcome-file> Element
o <welcome-file>index.jsp</welcome-file>
o <welcome-file> specifies the relative path of a single welcome file. Welcome file is
provided when the web application is accessed using only the domain name or with
any other URL that ends with a slash.

ADITI CHIKHALIKAR 42
39. Create a servlet code to calculate Square and Square Root of a number. Take number as
user input.
Answer: [Note: Write both codes, even if servlet is written in question.]
index.html
<!DOCTYPE html>

<html>
<head>
<title>Square and Square Root</title>
</head>
<body>
<form action="Calculate">
Enter number:<input type="text" name="txtnum"><br> <br>

<input type="reset">
<input type="submit" value="Calculate">
</form>
</body>
</html>

Calculate.java

package demoC;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Calculate extends HttpServlet {


protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Integer num=Integer.parseInt(request.getParameter("txtnum"));
out.println("Square: "+(num*num)+"<br> Square Root: "+Math.sqrt(num));
}

For Cube: (num*num*num)


For Cuberoot: Math.cbrt(num);

ADITI CHIKHALIKAR 43
40. Write a servlet code to display Square and Square root of numbers between 25 and 365 in
tabular form.
import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{
PrintWriter out = response.getWriter();
out.println("<table border=1>");
for(int i=25; i<=365; i++){
out.println("<tr><td>"+(i*i)+"</td><td>"+Math.sqrt(i)+"</td></tr>");
}
out.println("</table>");

41.Write a servlet code to print tables from 2 to 10.

package demoCal;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TableServlet extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// int num;
// num=Integer.parseInt(request.getParameter("num"));
for(int j=2;j<=10;j++)
{
for(int i=1;i<=10;i++)
{
out.println(j+" x "+i+" = "+(j*i)+"<br>");
}

}
}
}

+ Programs in journal 1A, 1B

ADITI CHIKHALIKAR 44
Chapter 6
42. What is JDBC? Explain architecture of JDBC in Detail? OR JDBC Components U
Answer:
What is JDBC?
• Java Database Connectivity is a Java API for executing SQL statements and supports basic
SQL functionality.
• JDBC is API that defines interface and classes for writing database applications in java by
making database connections.
• It is a program designed to access many popular DB products on a number of OS platforms.
• We can send SQL,PL/SQL statements to almost any relational DB.
• In 1996, JavaSoft, released its first version of the JDBC kit. JDBC stands for Java Data Base
Connectivity. This is actually an API, which consists of a set of Java classes, interfaces and
exceptions designed to perform actions against any database.
• Applications developed with Java and JDBC are platform and database vendor independent
i.e. the same Java program can run on a PC, a workstation or a network computer and can
connect to any vendor's DBMS simply by changing the JDBC middleware.
• JDBC is today a mature and well-accepted table data, access and standard.

JDBC Architecture
• JDBC supports both two-tier and three-tier processing models for database access.
• JDBC architecture consists of two layers:
o JDBC API – Connects the application to the JDBC Manager.
o JDBC Driver API – Connects the JDBC Manager to the actual driver.
• JDBC uses a DriverManager and database-specific drivers to connect to different
databases transparently.
• The DriverManager ensures the correct driver is used for each database and can support
multiple concurrent drivers.

ADITI CHIKHALIKAR 45
Components of JDBC Architecture
• JDBC API
• Provides functionality to access relational databases from Java.
• Consists of two main packages:
o java.sql
o javax.sql (for client-side and server-side support)
• JDBC Driver Manager
• Manages the list of available database drivers.
• Matches each application request with the proper database driver using a sub-protocol.
• Loads drivers listed in the system property automatically.
• JDBC Driver
• Acts as an interpreter that converts JDBC method calls into DBMS-specific commands.
• Implements JDBC interfaces/classes for a specific database vendor.
• Translates JDBC calls into network protocols, database protocols, or library API calls.
• Enables database independence – only the driver (and some code) needs to change if the
backend DBMS changes.
• Java programs load the required driver before establishing the connection, and
DriverManager routes calls to it.

43. Discuss the advantages of JDBC. U


Answer:
Advantages of JDBC:
• JDBC provides database independence, allowing access to various DBMS without relying
on proprietary architectures.
• Supports use of already installed databases and enables access to data across multiple
database systems.
• Combines Java API and JDBC API for easier, cost-effective, and efficient application
development.
• Simplifies complex data access tasks with a straightforward and easy-to-learn API.
• No special configuration is needed on the client side; connections are handled via JDBC
URLs or DataSource objects.

ADITI CHIKHALIKAR 46
• Fully integrated into the Java EE platform, supporting the Write Once, Run Anywhere
(WORA) paradigm.
• Provides metadata access, facilitating the development of sophisticated and dynamic
database applications.
• JDBC drivers are easy to use and typically don’t require special installation.
• Database connections are managed using simple URL-based configuration.
• Helps in building portable, maintainable, and scalable enterprise applications.

44. Important classes and interfaces related to JDBC.


Answer:
Important Classes/Interfaces:
The following are important JDBC classes/interfaces in the java.sql package:
• Driver: Gives JDBC a launching point for database connectivity by responding to
DrvierManager connection implementation in question requests and providing information
about the implementation in question.
• DriverManager: Actually keeps a list of classes that implement the Driver interface. When
an application is run, DriverManager loads all the drivers found in the memory. When opening
a connection to a database DriverManager selects the most appropriate driver from the
previously loaded drivers
• Connection: Represents a connection with a data source. This interface can be used to
retrieve information regarding the tables in the database to which connection is opened
• Statement: Represents static SQL statement that can be used to retrieve ResultSet object(s).
The objective of Statement interface is to pass to the database the SQL command for
execution and to retrieve output results from the database in the form of a ResultSet
• ResultSet: Is a database result set generated from a currently executed SQL statement. The
data from the query is delivered in the form of a table. The rows of the table are returned to
the program in sequence
• PreparedStatement: Is an SQL statement that is pre-compiled and stored. This object can
then be executed multiple times much more efficiently than preparing and issuing the same
statement each time it is needed. Therefore, it is a higher performance alternative to Statement
object
• CallableStatement: Represents a stored procedure. It can be used to execute stored
procedures in a RDBMS that supports them

45. Enlist and explain the steps of Database connectivity using JDBC API.
Answer:
Fundamental Steps in JDBC / Accessing Database:

The fundamental steps involved in the process of connecting to a database and executing a query
consist of the following:
• Import JDBC packages.
• Load and register the JDBC driver.
• Open a connection to the database.
• Create a statement object to perform a query.
• Execute the statement object and return a query resultset.
• Process the resultset.

ADITI CHIKHALIKAR 47
• Close the resultset and statement objects.
• Close the connection.

● Step 1:
○ To start with java JDBC connection to the database, we must first import java.sql
package.
○ java.sql Package: This API is a core API that is compatible with any driver that uses
JDBC technology
○ javax.sql Package: This package is an Optional Package API, which extends the
functionality of the JDBC API from a client-side API to a server-side API. It provides
scrollable result sets and cursor support
● Step 2:
○ Loading a database driver:
■ The driver class is loaded by calling Class.forName() with the driver name as
an argument.
■ The return type of the Class.forName(String classname) method is “Class”
& it is present in java.lang package.
■ For ex.
● Class.forName(“com.mysql.jdbc.Driver”);
● Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
● Class.forName("oracle.jdbc.driver.OracleDriver“);
■ We will use:
Class.forName("com.mysql.jdbc.Driver");
■ Class.forName() is a static method. This instructs the JVM to dynamically
locate, load and link the class specified to it as a parameter.
■ When the driver class is loaded into memory, it creates an instance of itself
and registers with java.sql.DriverManager as an available database driver.
● Step 3:
○ Creating Jdbc Connection
■ A JDBC driver must be loaded first before establishing a connection to a
database.
■ A database URL is used to identify and connect to a specific database.
■ Syntax: [For Database URL] jdbc:<SubProtocol>: <SubName>
■ Here,
● jdbc indicates that JDBC is being used to establish the database
connection
● SubProtocol is the name of the database the developer wants to
connect to. Example: mysql, oracle, odbc and so on
● SubName is typically a logical name or alias, which provides
additional information on how and where to connect
■ DriverManager Class
● The DriverManager class manages the set of JDBC drivers available.
● Used to connect Java applications to JDBC drivers.
● Uses the method getConnection() to establish a connection.
● Returns a Connection object for interaction with the database.
■ A Java application can have:
● One or more connections to the same database.
● Connections to different databases concurrently.
■ The getConnection() method:

ADITI CHIKHALIKAR 48
● Internally queries each registered driver.
● Locates the driver that recognizes the specified URL.
● Uses that driver to return a Connection object.
○ Jdbc URL
■ JDBC uses a URL to identify the database connection.
■ Each driver has its own sub protocol
■ each sub protocol has its own syntax for the source
○ For example.
■ For MS Access/SQL server Connection
Connection con = DriverManager.getConnection("jdbc:odbc:dsn_name");
○ For MySQL Connection
Connection con= DriverManager.getConnection(“URL of DB”,”loginname”,”passwrd”);

We Write:
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentMarks","root","root"
);

● Step 4:
○ Creating JDBC Statement Object:
■ Once connection is obtained we can interact with the database. Connection
interface defines methods for interacting with the database through the
established connection.
■ To execute SQL statements, we have 3 kinds of statements:
■ Standard Statement:
● It executes simple SQL queries without parameters. This statements
creates an SQL Statement object.
Syntax: Statement stmt=con.createStatement();
• Statement objects are never instantiated directly.
• A query that returns data can be executed using executeQuery() of
Statement. This method executes the statement and returns
java.sql.ResultSet that encapsulates the retrieved data.
• The following code spec defines ResultSet object that encapsulates
the retrieved data:
• ResultSet rs = stmt.executeQuery("SELECT * FROM Books");
• For inserts, updates or deletes, use executeUpdate(). executeUpdate()
accepts an SQL statement that contains user instructions to insert,
update or delete table data.
b) Prepared Statement:
● It executes a precomplied SQL queries with or without parameters. It
returns PreparedStatement object.

ADITI CHIKHALIKAR 49
● A Prepared Statement is used for an SQL statement, which must be executed
multiple times .
● When a prepared statement is created, the SQL statement is sent to the
database for pre-compilation [if this is supported by the JDBC driver].
● As they are precompiled, Prepared Statement executes much faster than
standard SQL statements.
● The question marks in the PreparedStatement syntax represent dynamic
query parameters. These parameters can be changed each time the prepared
statement is called.
Syntax:
PreparedStatement pstmt= con.prepareStatement(“insert into detail values(?,?,?)”);
pstmt.setInt(1, x);
pstmt.setString(2, y);
pstmt.setInt(3, x);
c) Callable Statement:
■ Callable Statement is used to execute SQL stored procedures.
■ Methods are provided to specify input parameters and retrieve return values.
■ Callable Statement object extends PreparedStatement and therefore, inherits
its methods.
Syntax:
CallableStatement cstmt= con.prepareCall(“{call getEmployee(?,?)}”);
● Step 5:
○ Executing SQL Statement:
The Statement class has three methods for executing statements
a) executeQuery()- for select statement.
b) executeUpdate()- for creating or modifying tables.
c) execute()- executes SQL statement that is written as String object.
● Step 6:
- Take data
○ executeUpdate() always return integer value indicating how many row affected.
○ executeQuery()- always returns ResultSet object which hold table data.
○ execute()- always return Boolean value .
○ ResultSet provides access to a table of data generated by executing a Statement. The
table rows are retrieved in sequence. The next() method is used to successively step
through the rows of the tabular results.
○ ResultSet is a cursor [i.e. a specific place in memory), which holds SQL query
output. ResultSet.next() can be used to navigate across data rows in the opened
cursor one row at a time, starting from the topmost row. ResultSet object also has
many other methods for retrieving data from the current row. getString() and
getObject() are among the most frequently used for retrieving specific column
values from a data row.
○ For ex.
ResultSet rs= stmt.executeQuery(“select * from tablename”);
while(rs.next())
{
String name = rs.getString("name");
}
Step 7: Close The Connection:

ADITI CHIKHALIKAR 50
■ Database is valuable resource and also consumes lot of memory for creation
and execution, therefore it is necessary to close the connection.
■ Connection object has a built-in method, close() for this purpose.
■ In addition to closing the database connection, application code spec, should
explicitly close all Statement and ResultSet objects using their close()
methods.
Syntax: rs.close();
stmt.close();
con.close();

46. List and explain four types of JDBC drivers. OR Write short note on JDBC Driver. Explain
its types and advantages. OR Explain Type1/ Type2/ Type3/ Type4 Driver.
Answer:
JDBC Type 1- JDBC-ODBC Driver
• Acts as a bridge between JDBC and ODBC (Open Database Connectivity).
• Uses standard ODBC drivers to enable JDBC access to database tables.
• Translates JDBC calls into ODBC calls, which are then sent to the respective ODBC
driver.
• Requires native ODBC libraries, drivers, and support files to be installed and
configured on each client machine.
• Converts JDBC API calls into ODBC function calls, typically using Microsoft's
ODBC interface.
• ODBC binary code must be present on every client system using this driver.
• The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
• The Bridge driver is not coded completely in Java; So Type 1 drivers are not portable.
• It is comparatively slowest than the other driver types. : This driver delegates the
work of data access to ODBC API. They are the slowest database access API of all,
due to the multiple levels of translation that have to occur.
• The client system requires the ODBC Installation to use the driver.

ADITI CHIKHALIKAR 51
JDBC Type 2 – Java Native Interface Driver
• Converts JDBC API calls into DBMS-specific client API calls.
• Uses Java Native Interface (JNI) to interact with native database libraries.
• Requires native binary code to be installed on each client machine.
• Similar to Type 1 (bridge driver), it needs native database client libraries for proper
functioning.
• Offers better performance than Type 1 but lacks portability due to native
dependency.

• This type of divers are normally offer better performance than the JDBC-ODBC
Bridge as the layers of communication are less than that it and also it uses
Resident/Native API which is Database specific.

• Mostly out of date now.


• It is usually not thread safe.
• This API must be installed in the Client System; therefore this type of drivers cannot
be used for the Internet Applications.
• Like JDBC-ODBC Bridge drivers, it is not coded in Java which cause to portability
issue.
• If we modify the Database then we also have to change the Native API as it is specific
to a database.

ADITI CHIKHALIKAR 52
JDBC Type 3 – Java Network Protocol/ Net Protocol Driver/ Middleware Driver
• Written in pure Java, making it platform-independent.
• Uses a vendor-independent network protocol to communicate with JDBC
middleware on a server.
• The middleware server translates JDBC calls into DBMS-specific function calls.
• Sends JDBC API calls to a middle-tier Net Server, which forwards them to the
appropriate DBMS.
• No native database libraries are required on the client machine.
• No client-side installation is needed, making it ideal for Internet-based
applications.
• Supports transparent access to multiple databases from a single application.
• This type of driver is server-based and uses a middle-tier server to communicate
with the database.
• Most efficient among multi-database access scenarios due to centralized
management.
• Written entirely in Java—hence portable and suitable for web applications.
• No vendor database library needed on the client side.
• The Net protocol is designed to make the client driver small and fast.
• Supports enterprise-level features like caching, load balancing, etc.
• Provides system administration features such as logging and auditing.
• Allows access to multiple databases using a single driver.
• This driver requires a separate middleware server (JDBC net server) to be
installed and maintained.
• Traversing the ResultSet may be slower, as data must pass through the
intermediate server, potentially increasing latency.

ADITI CHIKHALIKAR 53
JDBC Type 4 – Java Database Protocol / Native Protocol Driver
• Written in pure Java and communicates directly with the database using its native
protocol (e.g., Oracle's SQL*Net).
• Most efficient and commonly used among all driver types.
• Converts JDBC API calls directly into the DBMS-specific network protocol, with
no middle tier.
• Enables direct connection between client applications and the database server.
• Does not require native database libraries on the client machine.
• Can be easily deployed over the Internet.
• Installs inside the JVM of the client, ensuring portability.
• Offers better performance than Type 1 and Type 2 drivers, avoiding conversion
overhead.
• Unlike Type 3, it does not require middleware or associated software to function.
• Performance is generally very good due to direct communication with the
database.
• Fully written in Java for platform independence and easy deployment.
• Ideal for web applications as it eliminates deployment and admin complexity.
• Has fewer translation layers, avoiding overhead from converting to ODBC or
native APIs.
• No special software installation is required on either the client or the server.
• Drivers can be downloaded dynamically, making them flexible and easy to
distribute.
• Requires a separate driver for each database type (e.g., one for Oracle, another for
MySQL, etc.).
• Database-specific nature means less flexibility if the application needs to support
multiple DBMSs.

ADITI CHIKHALIKAR 54
47. What is a JDBC Statement object? Explain its 3 types. OR Explain JDBC statement object
with its types.
Answer:

○ Creating JDBC Statement Object:


■ Once connection is obtained we can interact with the database. Connection
interface defines methods for interacting with the database through the
established connection.
■ To execute SQL statements, we have 3 kinds of statements:
■ Statement:
● It executes simple SQL queries without parameters. This statements
creates an SQL Statement object.
Syntax: Statement stmt=con.createStatement();
• Statement objects are never instantiated directly.
• A query that returns data can be executed using executeQuery() of
Statement. This method executes the statement and returns
java.sql.ResultSet that encapsulates the retrieved data.
• The following code spec defines ResultSet object that encapsulates
the retrieved data:
• ResultSet rs = stmt.executeQuery("SELECT * FROM Books");
• For inserts, updates or deletes, use executeUpdate(). executeUpdate()
accepts an SQL statement that contains user instructions to insert,
update or delete table data.
b) Prepared Statement:
● It executes a precomplied SQL queries with or without parameters. It
returns PreparedStatement object.
● A Prepared Statement is used for an SQL statement, which must be executed
multiple times .
● When a prepared statement is created, the SQL statement is sent to the
database for pre-compilation [if this is supported by the JDBC driver].
● As they are precompiled, Prepared Statement executes much faster than
standard SQL statements.
● The question marks in the PreparedStatement syntax represent dynamic
query parameters. These parameters can be changed each time the prepared
statement is called.
Syntax:
PreparedStatement pstmt= con.prepareStatement(“insert into detail values(?,?,?)”);
pstmt.setInt(1, x);
pstmt.setString(2, y);
pstmt.setInt(3, x);
c) Callable Statement:
■ Callable Statement is used to execute SQL stored procedures.
■ Methods are provided to specify input parameters and retrieve return values.
■ Callable Statement object extends PreparedStatement and therefore, inherits
its methods.
Syntax:
CallableStatement cstmt= con.prepareCall(“{call getEmployee(?,?)}”);

ADITI CHIKHALIKAR 55
48. Explain following interfaces:
a. Connection
b. Statement
c. PreparedStatement
d. ResultSet
e. ResultSetMetaData

• Provides metadata (information about columns) of a ResultSet.


• Obtained using ResultSet.getMetaData().
• getColumnCount() returns the number of columns.
• getColumnName(int) returns column name.
• getColumnTypeName(int) returns SQL type name (e.g., VARCHAR, INT).
• getColumnType(int) returns SQL type code (e.g., java.sql.Types.VARCHAR).
• isNullable(int) returns whether the column can be NULL.

49. Explain RowSet and its type in JDBC.


• RowSet is an interface in the javax.sql package, unlike ResultSet which is in java.sql.
• Introduced in JDK 5, it provides a more flexible, JavaBean-compatible, and scrollable
version of ResultSet.
• RowSet can be used connected or disconnected from the database.
• Implements JavaBean features, such as property change events and listeners.
• Simplifies navigation and manipulation of tabular data retrieved from the database.
• Supports event listeners, making it suitable for GUI applications.
• Acts as a wrapper around ResultSet, adding more capabilities.
Features of RowSet
• Extends the functionality of ResultSet.
• Can operate without a continuous database connection (disconnected RowSet).
• Supports JavaBeans properties (setURL, setUsername, setPassword, etc.).
• Supports scrolling and updating by default.
• Easy to use with GUI components due to its event-based architecture.
• Can be serialized for network transmission or storage.
• Suitable for cached data manipulation in offline mode.
• Provides type-safe, metadata-aware, and bindable structure.
• Created using RowSetProvider.newFactory().createJdbcRowSet().
RowSet Type Description
1. JdbcRowSet Connected RowSet. Works like a ResultSet. Always connected to DB.
2. CachedRowSet Disconnected RowSet. Can operate without a DB connection after being
populated.
3. WebRowSet Subtype of CachedRowSet that can be serialized as XML for web
transmission.
4. FilteredRowSet Allows filtering rows using a filter interface.
5. JoinRowSet Can join multiple RowSets without SQL JOIN. Useful for in-memory joins.

50. Write a program to accept details of a person and using servlet and store those details in
database.
51. Write a servlet program in Java using JDBC to accept the Customer details such as
Customer ID, Customer Name and Contact No. from user via HTML form and store the
same in the database.

ADITI CHIKHALIKAR 56

You might also like