100% found this document useful (1 vote)
1K views76 pages

Enterprise Java Sem: V

Uploaded by

arnav
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
100% found this document useful (1 vote)
1K views76 pages

Enterprise Java Sem: V

Uploaded by

arnav
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/ 76

www.acuityeducare.

com

Acuity Educare

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 1

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Q.1 What are the various factors important before deciding on the number of tiers in application
architecture?

The various factors important before deciding on the number of tiers in application architecture are:
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 time to improve
performance and provide better functionality to the client.

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.

Q.2 Write a short note on Single tier architecture.

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
Hence in a 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:
i. 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.

ii. 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.

iii. Running all of the site's components on a single computer also limits expansion and optimization
possibilities

Page 1 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Q. 3 Explain two tier architecture with its advantages and disadvantages.

In Two Tier architecture, an application is divided into two components:


1. Client
i. Implements the user interface
ii. Contains business logic
2. Server
i. 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:


i. The User Interface is always physically located in the user's desktop [i.e. the Client].
ii. The database management services are always physically located on a Server

Advantages:
i. Adds additional security by removing sensitive customer data from the single computer
ii. Having the database on a separate computer improves the overall performance of the site
iii. Allows optimizing each machine for more specific performance requirements

Disadvantages:
i. The increased cost and complexity of the architecture
ii. 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.

Page 2 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Q. 4 Write a short note on three tier architecture.

Three Tier architecture is the evolution of two tier applications. Logically the application is divide into
three constituent layers:
User Services - Presentation Layer: Provides service such as the Graphical User Interface and
other automation tasks that the application has to perform.
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
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.
Each of the three layers can now be optimized for peak operating efficiencies. The main functions
of:
i. The Presentation Layer is network I/O
ii. The Business Layer is CPU-intensive
iii. The Data Layer is disk I/O intensive

Q. 5 What is need of multi‐ tier architecture and explain its functionality.

1. Client Tier: This tier represents all device or system clients accessing the system or the
application. A client can be a Web browser, a Java or other application, a Java applet, a WAP
phone, a network application, or some device introduced in the future. It could even be a batch
process.

2. Presentation Tier: This tier encapsulates all presentation logic required to service the clients that
access the system. The presentation tier intercepts the client requests, provides single sign-on,
conducts session management, controls access to business services, constructs the responses,
and delivers the responses to the client. Servlets and JSP reside in this tier. Note that servlets and
JSP are not themselves UI elements, but they produce UI elements

3. Business Tier: This tier provides the business services required by the application clients. The tier
contains the business data and business logic. Typically, most business processing for the
application is centralized into this tier It is possible that, due to legacy systems, some business
Page 3 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

processing may occur in the resource tier. Enterprise bean components are the usual and preferred
solution for implementing the business objects in the business tier.

4. Integration Tier: This tier is responsible for communicating with external resources and systems
such as data stores and legacy applications. The business tier is coupled with the integration tier
whenever the business objects require data or services that reside in the resource tier. The
components in this tier can use JDBC, J2EE connector technology, or some proprietary middleware
to work with the resource tier.

5. Resource Tier: This is the tier that contains the business data and external resources such as
mainframes and legacy systems, business-to-business (B2B) Integration systems, and services
such as credit card authorization.

The layered architecture provides following benefits:


 Easier to understand and Traceable Code for developers.
 Easier to write the applications.
 Easier to test the applications.
 Easier to extend the business rules on a particular domain object.

Q. 6 What are Java EE containers?

Java EE containers are the interface between the component and the lower-level functionality of the
application server provided by the platform to support that component and API . The functionality of
the container is defined by the platform to provide more productivity, and is different for each
component type. The server allows the different component types to work together to provide the
enhancement of functionality in an enterprise application.

The Web Container: The web container is the interface between web components or API and the
web server. A web component can be a JSP page, or a JavaServer Faces Facelets page, and
servlet. The web container manages the processes of Request & Response in the component’s
lifecycle, dispatches requests to application components, and provides interfaces to context data,
such as information about the current request.

The Application Client Container: The application client container is the interface between Java EE
applications and clients/browsers, which are special Java SE applications that use Java EE server
components with more API’s , and the Java EE server. The application client container runs on the
client machine, and is the gateway between the client application and the Java EE server
components that the client/browsers uses
Page 4 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Key points of Container:


 In Java EE security models configure a web component or EJB so that system resources are
accessed at client side/browsers only by authorized users.
 The Java EE transaction model provides relationships among methods/functions that
communicate a single transaction so that all methods/functions in single transaction are treated as a
single unit.
 The Java EE can be remotely connectivity model manages low-level communications between
clients and EJB.

Q. 7 Explain CGI technology and what are its disadvantages?

1. CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each & every request, it starts a new
process or creates a new Thread for every request. i.e. Number request coming to CGI, a number of
newly processes or threads to create. CGI will get more load & responses are slow or its processing
task may be heavy.
2. The Common Gateway Interface (CGI) provides the middleware between WWW servers and
external databases and information sources. The World Wide Web Consortium (W3C) defined the
Common Gateway Interface (CGI) and also defined how a program interacts with a Hyper Text
Transfer Protocol (HTTP) server.
3. The Web server typically passes the form information to a small application program that processes
the data and may send back a confirmation message. This process or convention for passing data
back and forth between the server and the application is called the common gateway interface
(CGI).
Disadvantages of CGI:
There are many problems in CGI technology:

1. If the number of clients increases, it takes more time to send the response
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent languages e.g. C, C++, perl.
4. CGI facing Network Traffic, because of heavy load. 5. Number request, Number of newly processes
so CGI contain heavy load.

Q.8 Write a short note on Servlet interface and explain its methods.

Servlet interface is a collection of empty method signatures.


A servlet must directly or indirectly [by subclassing the GenericServlet or HttpServlet class]
implement the servlet interface.
This interface holds method signatures that bring the following basic Servlet functionalities:
 Initializing a Servlet
 Handling a client request
 Destroying a Servlet

Page 5 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Following are the methods in this interface:


init() Is used for initializing the servlet parameters provided by
the ServletConfig object.
Is called only once when the Servlet is first loaded. It is
commonly used to initialize resources to be used by a
Servlet when requests are received.
For example, database or network connections, file
initialization and other environment settings.
None of the Servlets methods can be called unless the
Servlet is initialized using init().
destroy() destroy() is also called only once immediately before the
Servlet is unloaded.
Is used to clear all retained resources such as database
connection, threads, file handles and so on.
This method is overridden in order to free up any resources
being used by the Servlet.
service() Is the actual heart of the HTTP Request-Response model.
Is called to handle a single client request.
A Servlet receives request information through the
ServletRequest object and sends data back to the client
through the ServletResponse object.
getServletConfig() Provides the ServletConfig object for initializing the
Servlet’s parameters.
getServletInfo() Provides the Servlet metadata such as author, servlet
version and other copyright information.
This method needs to be overridden inside the Servlet for it
to
return the required information.

Q.9 Explain the life cycle of a servlet.


In Java Servlet, The web container maintains the life cycle of a servlet instance/Object. Following are
the Stages of life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

Stages of servlet life cycle

Page 6 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

 The servlet is in a new state if the servlet instance is created.


 After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks.
 When the web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded: In servlet while executing the servlet class first stage is i.e classloader is
responsible for loading the servlet class into RAM. servlet class is loaded when the first request
comes from the web container.
2) Servlet instance is created: After loading the servlet class web container creates the instance of a
servlet t class. The servlet instance/object is created only once in the servlet life cycle; the second
time request is not created.
3) init method is invoked: The web container/web server calls the init() method only once after
creating the servlet instance. Basically the init() method is used to initialize the servlet. init() method
is the content of the life cycle of the javax.servlet.Servlet interface. Syntax: public void
init(ServletConfig config)
4) service method is invoked: The web container/web server calls the service method each time
when a request for the servlet is received. If the servlet class or object is not initialized, again it
follows the first three steps as described above then calls the service method. If the servlet is
initialized, it calls the service method. Syntax: public void service(ServletRequest request,
ServletResponse response)
5) destroy method is invoked: The web container/web server calls the destroy method before
removing the servlet instance from the RAM. destroy() method gives the servlet an opportunity to
clean up any resource for example memory, thread etc.

Q. 10 . Explain various types of JDBC Drivers.

1. Type 1-JDBC-ODBC Bridge plus ODBC driver


This driver converts JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls that
are then passed to the ODBC driver. The ODBC binary code must be loaded on every client
computer that uses this type of driver.
Advantage:
The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Disadvantages:
The Bridge driver is not coded completely in Java: So Type 1 portable. It is not good for the Web
Application because it is not portable.

It is comparatively slowest than the other driver types. The client system requires the ODBC
Installation to use the driver.

Page 7 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

3. Type 2-Native-APV Partly Java driver


The driver converts JDBC API calls into DBMS precise client API calls Similar to the bridge driver,
this type of driver requires that some binary code be loaded on each client computer.

Advantage:
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.
Disadvantage:
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 specific to a database.

3. Type 3-JDBC-NA/Pure Java Driver


This driver sends JDBC API calls to a middle tier Net Server that translates the calls into DBMS
precise Network protocol. The translated calls are then sent to a particular DBMS.

Advantages:
 This type of drivers is the most efficient amongst all driver types.
 This driver is totally coded in Java and hence Portable. It is suitable for the web Applications.
 This driver is server based, so there is no need for any vendor, database library to be
present on client machines.

 With this type of driver there are many opportunities to optimize portability, performance, and
scalability.
 The Net protocol can be designed to make the client JDBC driver very small and fast to
load.
 This normally provides support for features such as caching, load balancing etc.
 Provides facilities for System administration such as logging and auditing.
 This driver is very flexible allows access to multiple databases using one driver.

Disadvantages:

Page 8 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

 This driver requires another server application to install and maintain. Traversing the
recordset may take longer, since the data comes through the back-end server.

4. Type 4 - Native-protocol/Pure Java driver

This driver converts JDBC API calls directly into the DBMS precise network protocol without a
middle tier. This allows the client applications to connect directly to the database server.

Advantages:
 The Performance of this type of driver is normally quite good.

 This driver is completely written in Java to achieve platform independence and eliminate
deployment administration issues. It is most suitable for the web.

 In this driver number of translation layers are very less i.e. type 4 JDBC drivers don't need to
translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server.

 We don't need to install special software on the client or server.

 These drivers can be downloaded dynamically.

Disadvantages:
With this type of drivers, the user needs a different driver for each database.

Page 9 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Q. 11 . Explain following interfaces:

a. Connection

In JDBC API a Connection interface is the session between a Java application and database. The
Connection interface is a factory of PreparedStatement, Statement, and DatabaseMetaData, that
means objects of Connection can be used to get the object of Statement and DatabaseMetaData.
Commonly used methods of Connection interface:
A) public Statement createStatement(): In Java creates a statement object that can be
used to execute SQL queries.
B) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type.
C) public void close(): closes the connection and Releases a JDBC resources immediately.

b. Statement

The Statement interface provides methods to execute queries with the database.
The statement interface is a factory of ResultSet i.e. it provides a factory method to get the object
of ResultSet.
Following are the important methods of Statement interface:
A) public ResultSet executeQuery(String sql): In Java is used to execute SELECT
query.
It returns the object of ResultSet when executing the query.
B) public int executeUpdate(String sql): In Java is used to execute specified query, it may
be create, drop, insert, update, delete.
C) public boolean execute(String sql): is used to execute queries that may return multiple
results from a database.

c. PreparedStatement

The PreparedStatement interface is a subinterface of Statement.


It is used to execute parameterized queries. example of parameterized query:
String sql="insert into emp values(?,?,?)";
In the above example parameters (?) are passed for the values. Its value will be set by calling
the setter methods of PreparedStatement.
The performance of the application will be faster if you use PreparedStatement interface
because the query is compiled only once.
Methods of PreparedStatement interface are:

Page 10 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

d. ResultSet

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, the cursor
points to the first row.
Following are the Commonly used methods of ResultSet interface:

Sr no Methods Description
1) public boolean next(): This method is used to move the cursor to
the one row next from the current position.
2) public boolean previous(): This method is used to move the cursor to
the one row previous from the current
position.
3) public boolean first(): This method is used to move the cursor to
the first row in the result set object.
4) public boolean last(): This method is used to move the cursor to
the last row in the result set object.
5) public boolean absolute(int This method is used to move the cursor to
row): the specified row number in the ResultSet
object.
6) public boolean relative(int This method is used to move the cursor to
row): the relative row number in the ResultSet
object, it may be positive or negative.
7) public int getInt(int This method is used to return the data of
columnIndex): specified column index of the current row
as int.
8) public int getInt(String This method is used to return the data of
columnName): the specified column name of the current
row as int.
9) public String getString(int This method is used to return the data of
columnIndex): the specified column index of the current
row as String.
10) public String This method is used to return the data of
getString(String the specified column name of the current
columnName): row as String

e. ResultSetMetaData

The metadata refers to the data about data. The ResultSetMetaData interface provides the
facility to get the information like table name, total number of column, column name and column
type etc. We can get the object of ResultSetMetaData by calling getMetaData() method of
ResultSet interface.
1. getTableName(int index): It returns the name of the table of the specified column index.
Syntax:
public String getTableName(int index) throws SQLException

2. getColumnCount(): It returns the no. of columns in the result set.


Syntax:

public int getColumnCount() throws SQLException

3. getColumnName(int index): It returns the name of the column at the specified column index.
Syntax:

Page 11 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

public String getColumnName(int index) throws SQLException

4. getColumnTypeName(int index): It returns the type of the column at the specified column index.
Syntax:
public String getColumnTypeName(int index) throws SQLException

Q. 12 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 doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
out.println("<table border=1>");
for(int i=25; i<=365; i++){
out.println("<tr><td>"+(i*i)+"</td><td>"+Math.sqrt(i)+"</td></tr>");
}
out.println("</table>");
}
}

Q. 13 List the tasks that Servlet can do?

Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it
could also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types
and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database, invoking a
Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
 Servlet is a web component that is deployed on the server to create a dynamic web page.
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other
clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters,
and other such tasks.

Q. 14 Write a short note on javax.servlet package.

1) In Java Servlet Containing API i.e the javax.servlet and javax.servlet.http packages represent
interfaces and classes for servlet API where to design java web applications.
2) The javax.servlet package contains so many interfaces and classes that are used by the servlet or
web container programming.
3) In the Javax.servlet package, the ServletRequest Interface is used to handle client requests to
access a servlet. It provides the information of a servlet like, parameter names, content type,
content length and values.
Page 12 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

4) In the Javax.servlet package, the ServletResponse interface defines an object to help a Servlet in
sending a response to the client/browser. It has various methods that help communicate a servlet to
respond to the client requests.
5) In the Javax.servlet package, the RequestDispatcher interface provides the facility of dispatching
the request to another resource , be it html, servlet or jsp. This interface can also be used to include
the content of another resource.
6) Following are the interfaces of javax.servlet package:
There are many interfaces in the javax.servlet package. They are as follows:
1. Servlet Interface.
2. ServletRequest.
3. ServletResponse.
4. RequestDispatcher.
5. ServletConfig
6. ServletContext
7. ServletRequestListener
8. ServletRequestAttributeListener
9. ServletContextListener
10.ServletContextAttributeListener
7) Following are the List of Classes in javax.servlet package
1. GenericServlet.
2. ServletInputStream.
3. ServletOutputStream.
4. ServletRequestWrapper.
5. ServletResponseWrapper.
6. ServletRequestEvent.
7. ServletContextEvent.
8. ServletRequestAttributeEvent.
9. ServletContextAttributeEvent.
10. ServletException.
11. UnavailableException.

Q. 15 Explain the architecture of JDBC. / Explain the architecture of Java Enterprise Application.

The JDBC API supports both two-tier and three-tier architecture of sql processing models for database
access data .
1. Two-tier Architecture:
 In the JDBC two-tier architecture model, a Java applet or application talks directly to the data
source.
 This requires a JDBC driver that can communicate with the particular data source/database being
accessed.
 A client sends a request to execute the database or other data source, and the results of those
statements are sent back to the user.
 The data source may be located on another machine to which the user is connected via a network.
This is referred to as a client/server configuration where they can communicate to each other .

Page 13 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

2. Three-tier Architecture:
 Three Tier architecture is the evolution of two tier applications.
 Logically the application is divide into three constituent layers:
a. User Services - Presentation Layer: Provides service such as the Graphical User Interface
and other automation tasks that the application has to perform.
b. 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
c. 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.
 Each of the three layers can now be optimized for peak operating efficiencies. The main
functions of:
 The Presentation Layer is network I/O
 The Business Layer is CPU-intensive
 The Data Layer is disk I/O intensive

Page 14 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Q. 16 What are the alternatives to CGI? Explain in detail.

Alternatives for CGI:


Several alternatives to CGI have appeared in recent years. They all build upon CGI's legacy and
provide their own approaches to the same underlying goal: responding to queries and presenting
dynamic content via HTTP. Most of them also attempt to avoid the main drawback to CGI scripts :
creating a separate process to execute the script every time it is requested.
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 require
an additional process. 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 ColdFusion, and developers can create
their own controls as extensions. 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.

Q. 17 Write short note on Part and WebConnection interfaces.

A. Part Interface (javax.servlet.http.Part):


This interface represents a part or form item that was received within a multipart/form-data POST
request.
Methods:
1. void delete(): Deletes the underlying storage for a file item, including deleting any
associated temporary disk file.
2. java.lang.String getContentType(): Gets the content type of this part.
3. java.lang.String getHeader(java.lang.String name): Returns the value of the
specified mime header as a String.
4. java.util.Collection<java.lang.String> getHeaderNames(): Gets the header names
of this Part.
5. java.util.Collection<java.lang.String> getHeaders(java.lang.String name): Gets the
values of the Part header with the given name.
6. java.io.InputStream getInputStream(): Gets the content of this part as an InputStream.
7. java.lang.String getName(): Gets the name of this part.
8. long getSize(): Returns the size of this fille.
Page 15 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

9. void write(java.lang.String fileName): A convenience method to write this uploaded


item to disk.
B. WebConnection Interface (javax.servlet.http.WebConnection):

This interface encapsulates the connection for an upgrade request. It allows the protocol handler to
send service requests and status queries to the container.
Methods:
1. ServletInputStream getInputStream(): Returns an input stream for this web connection.
2. ServletOutputStream getOutputStream(): Returns an output stream for this web connection.

Q. 18 Explain Deployment descriptor file with its elements.

Deployment Descriptor :
The deployment descriptor overrides configuration information specified through the annotation
mechanism.
Version 3.0 of the web deployment descriptor contains new attribute called metadata-complete on
the <web-app> element.
This attribute defines whether the descriptor is complete or whether the class files of the web
application should be examined for annotations that specify deployment information.
The element are as follows:
 <web-app> represents the whole application.
 <servlet> is sub element of <web-app> and represents the servlet.
 <servlet-name> is sub element of <servlet> represents the name of the servlet.
 <servlet-class> is sub element of <servlet> represents the class of the servlet.
 <servlet-mapping> is sub element of <web-app>.It is used to map the servlet.
 <url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.
Example:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0"
xmlns=http://java.sun.com/xml/ns/javaee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd">
<servlet>
<servlet-name>TWelcomeServlet</servlet-name> <servletclass>Servlet.TWelcomeServlet</servlet-
class>

</servlet>
<servlet-mapping>
<servlet-name>TWelcomeServlet</servlet-name>
<url-pattern>/TWelcomeServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

Q. 19 Explain RowSet and its type in JDBC.

RowSet
A RowSet object is a java class element and extends the ResultSet interface. The RowSet is majorly
classified into two types:

Page 16 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

 Connected Rowset : It is connected to the database connection object like the resultset. The
JDBCRow Set is the example of the connected RowSet.
 Disconnected RowSet: It only connects to the database whenever required and after finishing the
interaction they close the database connection.
There are three types of RowSet:
A. CachedRowset class: It is a disconnected rowset that caches its data in memory; not suitable for
very large data sets, but an ideal way to provide thin Java clients.
Example:
CachedRowSet tCachRs = new Cached RowSetImpl();
tCachRs.setUsername("tushar");
tCachRs.setPassword("sambare");
tCachRs.setUrl("jdbc:oracle://localhost:3306/test"); tCachRs.setCommand("select * from
Registration");
tCachRs.setPageSize(4);
tCachRs.execute();
while (tCachRs.nextPage()) {
while (tCachRs.next()) {
System.out.println(tCachRs.getString("username"));
}
}
B. JDBCRowSet class : It is a connected rowset that serves mainly as a thin wrapper around a
ResultSet object to make a JDBC driver look like a JavaBeans component.
Example:
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
tJdbcRs.setUsername("tushar");
tJdbcRs.setPassword("sambare");
tJdbcRs.setUrl("jdbc:oracle://localhost:3306/test");
tJdbcRs.setCommand("select * from Registration");
tJdbcRs.execute();
while(tJdbcRs.next()) {
System.out.println(tJdbcRs.getString("username"));
}
C. WebRowSet class: It is a connected rowset that uses the HTTP protocol internally to talk to a Java
servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly
update a set of rows.

Q. 20 Explain the architecture of JDBC.

 The main function of the JDBC API is to provide a means for the developer to issue SQL statements
and process the results in a consistent, database independently.
 JDBC provides wealthy object-oriented access to databases by defining classes and interfaces that
represent objects such as:
(1) Database connections, (2) SQL statements, (3) Result Set, (4) Database metadata, (5) Prepared
statements, (6) Binary Large Objects (BLOBs), (7) Character Large Objects (CLOBS). (8) Callable
statements, (9) Database drivers, (10) Driver manager.

Page 17 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

Layers of the JDBC Architecture


 The JDBC API uses a Driver Manager and database precise drivers to provide clear connectivity to
heterogeneous databases.
 The JDBC driver manager ensures that the correct driver is used to access each data source.
 The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
 The location of the driver manager with respect to the JDBC drivers and the Servlet is shown in
above figure.

Q. 21 Enlist and Explain the steps of database connectivity using JDBC API.

Steps of database connectivity using JDBC API:


To start with a java JDBC connection to the database, we must first import the "java.sql package" in
to our code. Like follows: import java.sql.*"; The star (*) indicates that all of the classes in the
package java.sql are to be imported.
1. Loading a database driver: We load the driver class by calling Class.forName() with the driver
class name as an argument. Once it is loaded, the Driver class creates an instance of itself. A client
can connect to Database Server through JDBC Driver. Most of the Database servers support ODBC
driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName
(String ClassName) method is "Class". Class is a class in java.lang package.Ex.
try {
Class.forName("sun.jdbc.odbc.Jdbc0dbcDriver"); //Or Other Driver Type
}
catch(Exception e){
System.out.println("Unable to load the driver class!");
}
2. Creating an oracle JDBC Connection: The JDBC DriverManager class defines objects which can
connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC
architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its
getConnection() method is used to establish a connection to a database. It uses a username,
password, and a jdbc url to establish a connection to the database and returns a connection object.
An application can have one or more connections with a single database, or it can have many
connections with different databases. A Connection object provides information about the database
tables, and fields. It also contains methods to deal with transactions.
JDBC URL Syntax:: jdbc: <subprotocol>: <subname>
Each driver has its own subprotocol & each subprotocol has its own syntax for the
source.
Example: sun.jdbc.odbc.JdbcOdbcDriver

try{
Connection
Page 18 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT1

tDbConn=DriverManager.getConnection(url,"loginName","Password")
}
catch(SQLException x ){
System.out.println( "Not able to find connection!");
}
3. Creating a JDBC Statement object : Once a 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 need to instantiate a Statement object from
our connection object by using the createStatement() method. As shown below.
Statement tStmt = tDbConn.createStatement();
A statement object is used to send and execute SQL statements to a database.
There are 3 kinds of Statements:
I. Standard Statement: It executes simple SQL queries without parameters. This statement creates
an SQL Statement object. A query that return the data can be executed using executeQuery()
Statement.
Syntax: Statement tStmt=tDbConn.createStatement();
Example: ResultSet trs=tStmt.executeQuery("Select * from Registration");
II. Prepared Statement: It execute a precompiled SQL queries with or without parameters. IT returns
a new PreparedStatement object. PreparedStatement objects are Precompiled SQL statements.
Syntax: PreparedStatement tPStmt=tDbConn.prepareStatement("Insert in to -");
III. Callable Statement: It executes a call to a database stored procedure. It returns a new
CallableStatement object. CallableStatement objects are SQL stored procedure call statements.
Syntax: CallableStatement tCStmt-tDbcon.prepareCall("(call getEmployee(?,?)}")
4. Executing a SQL statement with the Statement object & returning a JDBC resultSet: Statement
interface defines methods that are used to interact with database through the execution of SQL
statements. The Statement class has three methods for executing statements: executeQuery(),
executeUpdate(), and execute(). For a SELECT statement we use executeQuery method. For
creating or modifying tables we use executeUpdate method. The execute method executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data.
The next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
5. Closing the Database connection : Since database is valuable application resource and also
consumes lots of memory for creation and execution, it necessary to close the connection. The
Syntax for closing connection in JDBC is as follows:
 trs.close();
 tstmt.close()
con.close();

Page 19 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
www.acuityeducare.com

Acuity Educare

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 2

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q.1 Write a short note on RequestDispatcher Interface

In the Javax.servlet package, the RequestDispatcher interface provides the facility of dispatching the
request to another resource , be it html, servlet or jsp. This interface can also be used to include the
content of another resource.
For obtaining the object, two styles exist using ServletRequest object and ServletContext object. The
getRequestDispatcher(String path) method returns an object of Request Dispatcher and the same
method exist in both interfaces of ServletRequest and ServletContext. This can be chived like
following:

 javax.servlet.ServletContext.getRequestDispatcher(String path)

 javax.servlet.ServletRequest.getRequest Dispatcher(String path)


i. RequestDispatcher getRequestDispatcher(String path): Returns a RequestDispatcher
object that acts as a wrapper for the resource located at the given path. A
RequestDispatcher object can be used to forward a request to the resource or to include
the resource in a response. The resource can be dynamic or static.

ii. Request Dispatcher getNamed Dispatcher(String name): This method takes the name of
the Servlet (and JSP pages also) as parameter which is declared via Deployment
descriptor. It expects logical name of the destination servlet/JSP program as argument
value.

METHODS OF REQUESTDISPATCHER
Request Dispatcher is used in two cases:
1. To include the response (output) of one Servlet into another (that is, client gets the response of
both Servlets).
2. To forward the client request to another Servlet to honour (that is, client calls a Servlet but
response to client is given by another Servlet).

Page 1 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q. 2 What is a Cookie? Explain its types.

Cookies are text files stored on the customer's computer and are saved for various information
tracking purposes. Java Servlet transparently supports HTTP cookies.
 There are three steps involved in identifying recurring users:
 The server script sends a series of cookies to the browser. For example, name, age or identification
number, etc.
 The browser stores this information on the local machine for future use.
 The next time the browser sends a request to the web server, it will send the cookie information to
the server and the server will use that information to identify you.
 A servlet will access the cookie via the request.getCookies () request method which returns an array
of Cookie objects.
Some of the common uses of cookies are:
1. Session authentication uses cookie.
2. Personalized response to the customer based on their preferences, for example, we can set the
background color as a cookie in the customer's browser and then use it to customize the background
color of the response, image, etc.

Types of cookies:
There are 2 types of cookies in servlets:
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie: It is valid for one session only. It is removed every time the user closes the
browser.
Persistent cookie: It is valid for multiple sessions. It is not removed every time the user closes the
browser. It is removed only if the user logs out or logs out.

Q. 3 Write a short note on HttpSession.

The HTTP protocol is stateless, so we need to maintain state through session tracking techniques.
Each time the user requests the server, the server treats the request as a new request. Therefore, we
need to maintain a user's status to recognize a particular user.
 HTTP is stateless, which means that each request is treated as the new request.
 All requests and responses are independent. But sometimes it is necessary to monitor customer
activity on multiple requests. For example. When a user logs into your website, regardless of which
web page they visit after logging in, their credentials will remain on the server until they log off. Then
this is handled by creating a session.
 The session is used to store everything we can get from the client of all the requests the client
makes.
How to get the HttpSession object?:
The HttpServletRequest interface provides two methods to get the HttpSession object:
publicHttpSessiongetSession (): Returns the current session associated with this request or, if the
request does not have a session, create one.
publicHttpSessiongetSession (boolean creation): Returns the current HttpSession associated with this
request or, if there is no current session and create is true, it returns a new session.

Page 2 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q. 4 Explain various steps comprising life cycle of HttpSession.

Session life cycle:


• A visitor, using a web browser, requests a resource from the web server.
• The web server offers the authentication form which causes the visitor's web browser to display a
login form.
• The web browser returns the username and password, which are then returned to the web server.
• The web server returns a valid session ID to uniquely identify this visitor.
• The visitor's web browser sends any number of requests to the web server. The web server
identifies users based on session IDs.
• The visitor closes the browser without explicitly logging out.

Session Monitoring API:


The session monitoring API is based on the first four methods. This is to help the developer minimize
the overhead of session monitoring. This type of session tracking is provided by the underlying
technology. Let's take the example of the Java servlet. The servlet container handles session tracking
activity and the user does not need to explicitly do this using Java servlets. This is the best of all
methods, because all handling and errors related to session monitoring will be handled by the
container itself.

Session Monitoring Methods:


• User authentication: This is the very common way that the user can provide authentication
credentials from the login page and then we can pass the authentication information between the
server and the client to maintain the session. This is not a very effective method because it will not
work if the same user is logged in from different browsers.
 HTML hidden field: We can create a unique hidden field in the HTML and when the user
starts browsing we can set its unique value for the user and keep track of the session.
This method cannot be used with bindings because it requires the form to be submitted
each time a client-to-server request is made with the field hidden. Also, it's not safe
because we can get the hidden field value from the HTML source and use it to hack the
session.
 URL rewrite: We can add a session identifier parameter with each request and response
to keep track of the session. This is very tedious because we have to keep track of this
parameter in every response and make sure it doesn't collide with other parameters.
 Cookies: Cookies are small pieces of information sent by the web server in the response
header and stored in the browser's cookies. When the client makes an additional
request, it adds the cookie to the request header and we can use it to track the session.
We can maintain a session with cookies, but if the client disables cookies, it will not
work.
Session Management API:
The Session Management API builds on the previous methods for session monitoring. Some of the
major disadvantages of all of the above methods are:
1. Most of the time we don't just want to keep track of the session, we need to store some data in the
session that we can use in future requests. This will require a lot of effort if we try to implement it.
2. All of the above methods are not complete by themselves, they will not all work in a particular
scenario. So we need a solution that can use these session tracking methods to provide session
management in all cases.

Page 3 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q. 5 Explain the methods of cookie class that facilitative the creation, manipulation and deletion of
the cookies.

(1)Creation of a Cookie object: You call the cookie constructor with a cookie name and a cookie
value, both are strings.
Cookie cookie = new Cookie ("name", "value"); Note that neither the name nor the value must
contain spaces or any of the following characters: [] () =, "/? @:;
(2) Set the maximum age: Use setMaxAge to specify how long (in seconds) the cookie should be
valid.
The following would set a cookie for 24 hours. cookie.setMaxAge (60 * 60 * 24);
(3) Sending the cookie to the HTTP response headers: Use response.addCookie to add cookies in
the HTTP response header as follows
response.addCookie (cookie);
(4) Removing Cookies
Sometimes you may want to remove a cookie from the browser. You do so by setting the cookie
expiration time. You can set the expiration time to 0 or -1. If you set the expiration time to 0 the cookie
will be removed immediately from the browser. If you see the expiration time to -1 the cookie will be
deleted when the browser shuts down.
Cookie cookie = new Cookie("uid", "");
cookie.setMaxAge(0);
response.addCookie(cookie);

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


Blocking I/O?

Non-blocking I/O was introduced in Servlet 3.1to develop scalable applications, Servlet 3.0 allowed
asynchronous request processing, but the API allowed only traditional 1/0, which can restrict scalability
of your applications. In a typical application, ServletInputStream is read in a while loop. However, if the
incoming data is blocked or is streamed slower, the server thread must wait for the data. The same
situation can happen if the data is written to ServletOutputStream.
Servlet 3.1 resolves the problem by adding event listeners: ReadListener and WriteListener interfaces.
You register these event listeners by using ServletInputStream.setReadListener and
ServletOutputStream.setWriteListener.
The listeners have callback methods that are invoked when the content is available to be read or that
can be written without blocking.
The main idea of these technologies is to avoid threads blocking. That's important because blocked
threads waste resources, threads' memory and processor time during threads context switching. So in
some cases it's possible to increase servlet performance without any costs.

ReadListener and WriteListener :

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Linked BlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener,
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;

public class ReadListenerImpl implements ReadListener {

Page 4 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

private ServletInputStream input = null; private HttpServletResponse res = null;

private AsyncContext ac = null;

private Queue queue = new LinkedBlockingQueue();

ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c)


{
input = in:
res = r;
ac = c;
}
public void onDataAvailable() throws IOException {

System.out.println("Data is available"); StringBuilder sb = new StringBuilder();

int len = -1;

byte b[] = new byte[1024];

while (input.isReady() && (len = input.read(b)) != -1) {


String data= new String(b, 0, len); sb.append(data);
}
queue.add(sb.toString());
}
public void onAllDataRead() throws IOException
{ System.out.println("Data is all read");

// now all data are read, set up a WriteListener to write


ServletOutputStream output = res.getOutputStream(); WriteListener writeListener = new
WriteListenerImpl(output, queue, ac); output.setWriteListener(writeListener);
}
public void onError(final Throwable t) {

ac.complete();

t.printStackTrace();
}
}

Q. 7 Explain the working of Non-Blocking I/O.

The basic flow for a servlet that calls an external REST service using an async HTTP client (for
example AsyncHttpClient) looks like this:

1. First of all the servlet where we want to provide async support should have @WebServlet
annotation with asyncSupported value as true.

2. Since the actual work is to be delegated to another thread, we should have a thread pool
implementation. We can create thread pool using Executors framework and use servlet context
listener to initiate the thread pool.

3. We need to get instance of AsyncContext through ServletRequest.startAsync() method.

Page 5 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

AsyncContext provides methods to get the ServletRequest and ServletResponse object references.
It also provides method to forward the request to another resource using dispatch() method.

4. We should have a Runnable implementation where we will do the heavy processing and then use
AsyncContext object to either dispatch the request to another resource or write response using
ServletResponse object. Once the processing is finished, we should call AsyncContext.complete()
method to let container know that async processing is finished.

5. We can add AsyncListener implementation to the AsyncContext object to implement callback


methods, we can use this to provide error response to client in case of error or timeout while async
thread processing. We can also do some clean-up activity here.

Q. 8 Explain about the file uploading feature of a servlet.

Uploading Files:
Upload is a term used to describe the process of transferring (sending) a file to another computer
through a modem or network. Below are a few examples of how a file may be uploaded to another
computer.
Examples of an Uploaded file:
• Over a network: If you are connected to a network you can upload a file to another computer or
share using file sharing.
• Over FTP, Telnet, or SSH: If you want to share something on the Internet, or have a personal web
page, you would upload the files to a computer or server connected to the Internet. FTP is the most
common method of uploading files.
Supporting file uploads is a very basic and common requirement for many web applications. The
Servlet 3.0 specification supports file upload out of the box, so any web container that implements the
specification can parse multipart requests and make mime attachments available through the
HttpServletRequest object.
A new annotation, javax.servlet.annotation.MultipartConfig, is used to indicate that the servlet on
which it is declared expects requests to made using the multipart/form-data MIME type. Servlets that
are annotated with @MultipartConfig can retrieve the Part components of a given multipart/form-data
request by calling the request.getPart(String name) or request.getParts() method.

Q 9 Explain using a code snippet the onDataAvailable() and onAllDataRead() methods of


ReadListener interface.

onDataAvailable is called when data can be read without blocking.


onAllDataRead is invoked when data for the current request is completely read.
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Linked BlockingQueue;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener,
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;

public class ReadListenerImpl implements ReadListener {

private ServletInputStream input = null; private HttpServletResponse res = null;

private AsyncContext ac = null;

Page 6 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

private Queue queue = new LinkedBlockingQueue();

ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c)


{
input = in:
res = r;
ac = c;
}
public void onDataAvailable() throws IOException {

System.out.println("Data is available"); StringBuilder sb = new StringBuilder();

int len = -1;

byte b[] = new byte[1024];

while (input.isReady() && (len = input.read(b)) != -1) {


String data= new String(b, 0, len); sb.append(data);
}
queue.add(sb.toString());
}
public void onAllDataRead() throws IOException
{ System.out.println("Data is all read");

// now all data are read, set up a WriteListener to write


ServletOutputStream output = res.getOutputStream(); WriteListener writeListener = new
WriteListenerImpl(output, queue, ac); output.setWriteListener(writeListener);
}
public void onError(final Throwable t) {

ac.complete();

t.printStackTrace();
}
}

Q. 10 Explain the following w. r. t. working with files in Servlet.

i) @MultipartConfigure - This annotation is used to indicate that the Servlet on which it is declared
expects requests to made using the multipart/form-data MIME type. We need to annotate File Upload
handler servlet with MultipartConfig annotation to handle multipart/form-data requests that is used for
uploading file to server.
ii) fileSizeThreshold - This attribute Specify size threshold when saving the upload file temporarily. If
the upload file's size is greater than this threshold, it will be stored in disk. Otherwise the file is stored
in memory. Size in bytes. Defaults is 0.
iii) location - This attribute Specify directory where upload files are stored. Default
iv) maxFileSize - This attribute Specify maximum size of an upload file. Size in bytes. Defaults is -1L
v) maxRequestSize - This attribute Specify maximum size of a request (including both upload files
and other form data). Size in bytes. Defaults is -1L.

Page 7 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q. 11 Write a servlet program GradeServlet.java that accepts Grade through radio buttons from
index.html page, if the string is “A”, “B”, “C” OR “D”, the program should dispatch the
direct to the Success.html page containing message “Congratulations, You Passed SEM V
exam”, else display “Try Again” and load index.html page in current servlet.

import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
String inp = hreq.getParameter("grade");
if(inp.equals("A") || inp.equals("B") || inp.equals("C") || inp.equals("D") )
{
RequestDispatcher rd = hreq.getRequestDispatcher("Success.html");
rd.forward(hreq, hres);
}
else {
out.println("<H1>TRY Again </h1>");
RequestDispatcher rd = hreq.getRequestDispatcher("index.html");
rd.include(hreq, hres);
}
}

Q. 12 Write a servlet program to create a session and display the following:


i) Session ID ii) New or Old iii) Creation Time

import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
HttpSession hs = hreq.getSession(true);
out.println("<br>Session ID "+ hs.getId());
out.println("<br>Is New "+ hs.isNew());
out.println("<br>Creation Time "+ new java.util.Date(hs.getCreationTime()));
}
}

Page 8 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

Q. 13 Explain Cookie class with its constructor and any five methods.

Cookies are small pieces of information sent by the web server in the response header and stored in
the browser's cookies. When the client makes an additional request, it adds the cookie to the request
header and we can use it to track the session. We can maintain a session with cookies, but if the
client disables cookies, it will not work.
Cookie() – Creating a Cookie Constructor

To creates a cookie Cookie() constructor is used, a small amount of information sent by a servlet to a
Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely
identify a client, so cookies are commonly used for session management.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they
handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
The servlet sends cookies to the browser by using the
HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP
response headers to send cookies to the browser, one at a time. The browser is expected to support
20 cookies for each Web server, 300 cookies total, and cookie size to 4 KB each. may limit

Syntax: public Cookie(java.lang.String name, java.lang.String value)


It constructs a cookie with a specified name and value.
Cookie (string name, string value) - constructs a cookie with a specified name and value.
public void setDomain (string schema)
• This method sets the domain to which the cookie applies, for example google.com.
public String getDomain ()
• This method gets the domain to which the cookie applies, for example google.com.
public void setMaxAge (expiration int)
• This method sets the time (in seconds) that must elapse before the cookie expires.
public int getMaxAge ()
• This method returns the maximum age of the cookie, specified in seconds. By default, -1 indicates
that the cookie will persist until the browser is deactivated.
public String getName ()
• This method returns the name of the cookie. The name cannot be changed after creation.

Q. 14 What is session tracking? What are the ways to track the sessions?

Session tracking is a mechanism that servlets use to maintain state about a series of requests from
the same user (that is, requests originating from the same browser) across some period of time.
Sessions are shared among the servlets accessed by a client. This is convenient for applications
made up of multiple servlets.
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 interface 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.
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user. A session usually corresponds to one user, who may visit a site many times.
The server can maintain a session in many ways such as using cookies or rewriting URLs.
This interface allows servlets to:

 View and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.

Page 9 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 2

 Bind objects to sessions, allowing user information to persist across multiple user connections.

Q. 15 Write short note on creation and invalidation of sessions.

By default every web server will have a configuration set for expiry of session objects. Generally it
will be some X seconds of inactivity. That is when the user has not sent any request to the server for
the past X seconds then the session will expire. When a session expires, the HttpSession object
and all the data it contains will be removed from the system. When the user sends a request after
the session has expired, server will treat it as a new user and create a new session.
Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession
provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at
logout. Or the application can have an absurd logic like after the user logins he can use the
application for only 30 minutes. Then he will be forced out. In such scenario you can use
getCreation Time().

Q. 16 Which points are important while uploading a file?

The following are the important points to note:


 The form method attribute must be set to POSTmethod and the GET method cannot be used.
 The form enctype attribute must be set to multipart / form-data.
 The module action attribute should be set to a servlet file that would handle uploading files to the
backend server. The following example uses the UploadServlet servlet to upload the file.
 To upload a single file, you need to use a single <input…/> with attribute type = "file". To allow
multiple file uploads, include more than one input tag with different values for the name attribute. The
browser associates each of them with a Browse button.

Page 10 of 10
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
www.acuityeducare.com

Acuity Educare

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 3

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q.1 What are the benefits of using JSP?/ Explain the reason why use JSP?

JSP has the following benefits:


1. Nobody can borrow the code: Since JSP page are written, runs and remains on the server, nobody
can copy the logic written in a jsp page even if they wanted to. Thus, security of the code is
maintained.
2. Faster loading of pages: Response page customization as requested by the user is done at the
server side itself thus no extra code or content is sent to the client side resulting in faster loading of
pages.
3. No Browser compatibility issues: Since JSP runs on the server side, the developer ends up sending
standard HTML to the user browser. This largely eliminates cross browser compatibility issues.
4. JSP Support: JSP is supported by a number of Web Servers. Built-in Support for JSP is available in
Java Web Server from Oracle.
5. Compilation: In JSP technology, each JSP page is compiled into executable code the first time it is
requested and invokes the resulting code directly on all subsequent requests. When coupled with a
persistent JVM, this allows the server to process request to JSP pages much faster.
6. Similarity to HTML: A JSP page looks a lot like a HTML or XML page except for the business logic
written either in scripting elements or JSP tags or both. Writing the business logic in JSP tags brings
consistency to the coding style used on the entire JSP page.
7. Separation of logic from view It enables to separate presentation layer with the business logic layer
in the web application.

Q. 2 Explain disadvantages of JSP.

The disadvantages of JSP are:


1. Attractive Java code: Putting Java code within a webpage is really bad design, but JSP makes it
tempting to do just that. Avoid this as far as possible.
2. Java Code Required: To do relatively simple things in JSP can actually demand putting Java code
in a page. A page needs to determine the context root of the current web application, perhaps to
create a link to the web applications,home page. This is done using Java code in JSP.
<a href=’<%=request.getContextPath%>/index.html’>Home Page Java code can be avoided by using
<jsp:getProperty> but that makes the code spec even more complex.
<a href=’ <jsp:getProperty name=”request” property=”contextPath”/>/index.html’>Home Page</a>
3. Simple Tasks are Hard to Code: Even including page headers and footers is a bit difficult with JSP.
In JSP the best way to do this is as follows:
<jsp:getProperty name=”request” property=”contextPath”/>
/*Some content here*/
<% @include file=”/footer.jsp”;%>
4. Occupies a lot of space: JSP pages require about double the disk space to hold the page. Because
JSP pages are translated into class files, the server has to store the resultant class files with the JSP
pages.
5. Debugging not easy: It is hard to trace JSP pages error because JSP pages are translated to
servlet before the compilation process.
6. Difficult Looping in JSP: Looping in JSP is a bit complicated.
7. Database Connection not easy: Database connectivity is not as easy as it should be. Most of the
servlet engine vendors do not support connection pooling natively, as of this day. Consequently, one
has to write a lot of custom code to do the job.

Page 1 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q. 3 Write a short note on life cycle of JSP.

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet. When the
browser asks for a JSP, JSP engine first checks whether it needs to compile the page. If the JSP is
last compiled or the recent modification is done in JSP, then the JSP engine compiles the page.
JSP Lifecycle follows the following steps:
1. Translation of JSP page
2. Compilation of JSP page(Compilation of JSP page into _jsp.java)
3. Classloading (_jsp.java is converted to class file _jsp.class)
4. Instantiation(Object of generated servlet is created)
5. Initialisation(_jspinit() method is invoked by container)
6. Request Processing(_jspservice() method is invoked by the container)
7. Destroy (_jspDestroy() method invoked by the container)
1. Translation of the JSP Page:
 A Java servlet file is generated from a JSP source file. This is the first step of JSP life cycle. In
translation phase, container validates the syntactic correctness of JSP page and tag files.
 The JSP container interprets the standard directives and actions, and the custom actions
referencing tag libraries used in this JSP page.
 When the conversion happens all template text is converted to println() statements and all JSP
elements are converted to Java code.
2. Compilation of the JSP Page:
 The generated java servlet file is compiled into java servlet class
 The translation of java source page to its implementation class can happen at any time between
the deployment of JSP page into the container and processing of the JSP page.
 Java servlet is compiled to a class file.
3. Class loading:
 Servlet class that has been loaded from JSP source is now loaded into the container
4. Instantiation:
 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the response to requests and other
events. Typically, a JSP container is built using a servlet container. A JSP container is an
extension of servlet container as both the container support JSP and servlet.
 A JSP Page interface which is provided by container provides init() and destroy () methods.
 There is an interface HttpJSPPage which serves HTTP requests, and it also contains the service
method.
5. Initialization:
public void jspInit()
{
//initializing the code
}
 jspinit() method will initiate the servlet instance which was generated from JSP and will be invoked
by the container in this phase.
 Once the instance gets created, init method will be invoked immediately after that
 It is only called once during a JSP life cycle, the method for initialization is declared as shown
above
6. Request processing:
void _jspservice
(HttpServletRequest request HttpServletResponse response) { //handling all request and

Page 2 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

responses }
 _jspservice() method is invoked by the container for all the requests raised by the JSP page
during its life cycle
 For this phase, it has to go through all the above phases and then only service method can be
invoked.
 It passes request and response objects
 This method cannot be overridden
 The method is shown above: It is responsible for generating of all HTTP methods i.eGET,
POST, etc.
7. Destroy:
public void _jspdestroy()
{
//all clean up code
}
 _jspdestroy() method is also invoked by the container
 This method is called when container decides it no longer needs the servlet instance to service
requests.
 When the call to destroy method is made then, the servlet is ready for a garbage collection
 This is the end of the life cycle.
 We can override jspdestroy() method when we perform any clean up such as releasing
database connections or closing open files.

Q. 4 Explain types of directives in JSP.

i. JSP directives serve special processing information about the page to the JSP Server.
ii. A JSP directive affects the overall structure of the servlet class.
iii. They do not produce any output that is visible to the client.
iv. It usually has the following form:
<%@ directive attribute = "value" %>
v. Directives can have a number of attributes which you can list down as key-value pairs and
separated by commas.
vi. The blanks between the @ symbol and the directive name, and between the last attribute and the
closing %>, are optional.
vii. There are three types of directive tag:

Sr Directive & Description


no.
1. <%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page,
and buffering requirements.
2. <%@ include ... %>
Includes a file during the translation phase.
3. <%@ taglib ... %>
Declares a tag library, containing custom actions, used in the page

1. Jsp Page Directive:


 The page directive is used to provide instructions to the container.
 These instructions pertain to the current JSP page.
 By convention, page directives are coded at the top of the JSP page.
 Following is the basic syntax of the page directive:
Page 3 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

<%@ page attribute = "value" %>


 The following are the most common attributes associated with the page directive:

Sr.No. Attribute and Example


1. language
Defines the programming language used in the JSP page.
Eg:< %@ page language="java"%>
2. import
Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
Eg:< %@ page import="java.util.Date" %>
3. contentType
Defines the character encoding scheme.
Eg:< %@ page contentType=application/msword %>
4. extends
Specifies a superclass that the generated servlet must extend.
Eg:< %@ page extends = "somePackage.SomeClass" %>
5. isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
Eg:< %@ page isErrorPage="true" %>
6. session
Specifies whether or not the JSP page participates in HTTP sessions.
Eg:< %@ page session = "true" %>
7. info
The info attribute lets you provide a description of the JSP.
Eg:< %@ page info = "This is a JSP Page" %>

2. JSP Include Directive:


 The include directive is used to include a file during the translation phase.
 This directive tells the container to merge the content of other external files with the current
JSP during the translation phase.
 Following is the basic syntax of the page include:
<%@ include file = "relative url">
 The file attribute:
A page-relative or context-relative URI path to the file that will be included at the current
position in the file.
 This attribute includes a static file ,merging its content with the including page before the
combined result is converted to a JSP page implementation class.
 A page can contain multiple include directives.
3. JSP Taglib Directive:
 The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides means for identifying the custom tags in your JSP page.
 Custom Tags allow developers to hide complex server side code spec from web designers.
 A taglib directive in a JSP is a link to an XML document that describes a set of custom tag.
 This XML document also determine which Tag Handler class implements the action of each
tag. The XML document names the tag library which holds the custom tags.
 The JSP engine uses this tag library to determine what to do when it comes across custom
tags.
 The taglib directive follows the syntax given below:
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
 The uri attribute:

Page 4 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

A Uniform Resource Identifier (URI) that identifies the Tag Library Descriptor ,which is used
to uniquely name the set of custom tags and inform the server what to do with the specified
tags.
 The prefix attribute:
It defines the prefix string in : pair and informs the JSP container which bits of markup are
custom tags.

Q. 5 What are the implicit objects in JSP?


 The JSP engine produces these objects during the translation phase (i.e., at the time of translation
from JSP to Servlet).
 They are being formed within the service method so that JSP developers can use them directly in
Scriptlet without declaration and initialization.
 There are 9 implicit objects in JSP as follows:

Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable

1. Out:
An out object is an implicit object for writing data to the buffer and sending output as a response to
the client's browser.
For servlet, we need to write:
PrintWriter out=response.getWriter();
But in JSP, we need to write:
<% out.print("JspWriter”); %>
2. Request:
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by
the web container.
It can be used to get request information such as parameter, header information, remote address,
server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
Syntax:
<%String name=request.getParameter("uname");%>
3. response:
In JSP, response is an implicit object of type HttpServletResponse.
The instance of HttpServletResponse is created by the web container for each jsp request. It can be
used to add or manipulate response such as redirect response to another resource, send error etc.
Syntax:
<%response.sendRedirect("http://www.google.com");%>
4. config:
In JSP, config is an implicit object of type ServletConfig.
This object can be used to get initialization parameter for a particular JSP page.
The config object is created by the web container for each jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
A config object is a configuration object of a servlet that is mainly used to access and receive
configuration information such as servlet context, servlet name, configuration parameters, etc. It
Page 5 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

uses various methods used to fetch configuration information.


Syntax:
<%String driver=config.getInitParameter("dname");%>
5. application:
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.
This object can be used to get initialization parameter from configuaration file (web.xml).
It can also be used to get, set or remove attribute from the application scope.
Syntax:
<%String driver=application.getInitParameter("dname");%>
6. session:
In JSP, session is an implicit object of type HttpSession.
The Java developer can use this object to set, get or remove attribute or to get session information.
Syntax:
<%String name=(String)session.getAttribute("user"); %>
7. pageContext:
In JSP, pageContext is an implicit object of type PageContext class.
The pageContext object can be used to set, get or remove attribute from one of the following
scopes:
 page  request  session  application.
In JSP, page scope is the default scope.
Syntax:
%<String name=(String)pageContext.getAttribute("user",PageContext.SESSI ON_SCOPE);%>
8. page:
In JSP, page is an implicit object of type Object class.
This object is assigned to the reference of auto generated servlet class.
It is written as: Object page=this;
For using this object it must be cast to Servlet type.
For example: <% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.
For example:
<% this.log("message"); %>
9. exception:
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception.
But it can only be used in error pages.
Syntax:
<%= exception %>

Q. 6 Explain disadvantages of JSTL.

1. Large complex JSP pages make use of JSTL tag libraries which exceeds class size limitation.
Because size of java class is limited.
2. JSTL is not so flexible and not as extensive as JSP Scriptlet. The JSTL is not nearly as evolved as
Java itself.
3. It is easier to programmer who knows HTML skill set. If JSTL get translated into Java code,
experienced programmer may wonder why he does not do that himself and save the time. So it may
difficult to carry out for experienced programmers.
4. JSP files that make use of JSTL will generate a great deal of overhead code.

Page 6 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q. 7 How JSP functions and Executes?

Functions of JSP:
The web server needs a JSP engine, ie, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages.
A JSP container works with the Web server to provide the runtime environment and other services a JSP
needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows
the position of JSP container and JSP files in a Web application.

The following steps explain how the web server creates the Webpage using JSP:
 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it

to a JSP engine. This is done by using the URL or JSP page which ends with jsp instead of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion
is very simple in which all template text is converted to println() statements and all JSP elements are
converted to Java code. This code implements the corresponding dynamic behaviour of the page.
 The JSP engine compiles the servlet into an executable class and forwards the original request to a
servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to the
web server by the servlet engine inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response
exactly as if it were a static page.

Q. 8 How to set and access the properties of java bean in JSP?

Setting the Properties of the Bean:


The JSP setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action:
 We can use JSP:setProperty after, but outside of, a JSP:useBean element, as follows:
<JSP:useBean id="myName" .../>
<JSP:setProperty name="myName" property="someProperty" /> In this case, the JSP:setProperty is
executed regardless of whether a new bean was instantiated or an existing bean was found.
 A second way in which JSP:setProperty can appear is inside the body of a JSP:useBean element,
as follows: <JSP:use Bean id="myName"...>
<JSP:setProperty name="myName" property="someProperty" .../>
</JSP:useBean>
Page 7 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

In this case the JSP:setProperty is executed only if a new object was instantiated, not if an existing one
was found. Property names will be passed to the appropriate setter methods.

In <JSP:setProperty> action the name attribute tells the bean whose property will be set. The Bean must
have been previously defined. The property attribute indicates the property that we want to set. A value of
"*" means that all request parameters whose names match the bean. The value attribute tells which value
is to be assigned to the given property. If the parameter's value is null, or the parameter does not exist,
then the setProperty action is The attribute param gives the name of the request parameter whose value
the property is to receive. We can't use both value and param, but it is permissible to use neither.

Accessing the Properties of the Bean:


The getProperty action is used to regain the value of a given property and converts to a string, and finally
inserts it into the output. The getProperty action has only two attributes, both of which are required.
Syntax: <JSP:use Bean id="myName" .../>
….
<JSP:getProperty name="myName" property="someProperty" .../>
In <ISP:getProperty> Action the name attribute gives the name of Bean that has a property to be retrieved.
In this case the Bean must have been previously defined. The property attribute states the name of the
Bean property to be retrieved.
Example: We have to define a TestClass bean which we will use in our example
// TestClass.java
package testAction;
public class TestClass {
private String msg = "Hello JSP...";
public String getMsg() {
return(msg);
}
public void setMsg(String msg) {
this.msg = msg;
}
}
We have to compile above code to generated TestClass.class file and make sure that copied
TestClass.class file in C:\apache-tomcat-7.0.2\ webapps\WEB-INF\classes\testAction folder and
CLASSPATH variable should also be set to this folder.
Now use the following code in home.JSP file which loads the bean and sets/gets a simple String
parameter:
<html> <head> <title>Using JavaBeans in JSP</title> </head>
<body> <center> <h2>Using JavaBeans in JSP</h2> <JSP:useBean id="test" class="test
Action.TestClass" />
<JSP:setProperty name="test" property="msg" />
<p>Here we got the message</p>
<JSP:getProperty name="test" property="msg" />
</center> </body> </html>

Now we have to load home.JSP, it would display following result:


Using JavaBeans in JSP
Here we got the message
Hello JSP...

Page 8 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q. 9 What are the types of Expression available in EL?

Types of Expressions:
The EL defines two kinds of expressions: value expressions and method expressions.
Value expressions can either yield a value or set a value.
Method expressions reference methods that can be invoked and can return a value.

1. Value Expressions:
Value expressions can be further categorized into rvalue and Ivalue expressions. The rvalue expressions
are those that can read data, but cannot write it. Ivalue expressions can both read and write data.
All expressions that are evaluated immediately use the $[] delimiters and are always rvalue expressions.
Expressions whose evaluation can be deferred use the #{ } delimiters and can act as both rvalue and Ivalue
expressions. Consider the following two value expressions:
$[customer.name}
#[customer.name]
The first expression accesses the name property, gets its value, adds the value to the response, and gets
rendered on the page. The same can happen with the second expression. However, the tag handler can
defer the evaluation of this expression to a later time in the page lifecycle, if the technology using this tag
allows.
In the case of JavaServer Faces technology (JSF), the latter tag's expression is evaluated immediately
during an initial request for the page. In this case, this expression acts as an rvalue expression. During a
postback request, this expression can be used to set the value of the name property with user input. In this
case, the expression acts as an Ivalue expression.

2. Method Expressions:
A method expression is used to invoke an arbitrary public method of a bean, which can return a result.
In JavaServer Faces technology, a component tag represents a component on a page. The component tag
uses method expressions to invoke methods that perform some processing for the component. These
methods are necessary for handling events that the components generate and validating component data,
as shown in this example:
<h:form> <h:inputText
id="name" value="#[customer.name]"
validator="#{customer.validateName]"/>
<h:commandButton id="submit" action="#[customer.submit]"/>
</h:form>
Method expressions can be used only in tag attributes and only in the follow ways:

 With a single expression construct, where bean refers to a JavaBeans compone and method refers
to a method of the JavaBeans component:
<some:tag value="#[bean.method]"/>
The is evaluated to a method expression, which is passed to the handler. The method represented by the
method expression can then be invoked later

 With text only.


<some tag value="sometext"/>
Method expressions support literals primarily to support action attribu JavaServer Faces technology.

Page 9 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q. 10 Write short note on Restriction, Projection and Partitioning Operators in EL.

1.Restriction Operators:
These are also referred as Filtering operators. These are an operation to restrict the result set such that it
has only selected elements satisfying a particular condition. There are two operators of this type.
I. Where: Filter values based on a predicate function.
II. OfType: Filter values based on their ability to be as a specified type.
Ex: products.where(p->p.productPrice >=100)

2. Projection Operators: Projection is an operation in which an object is transformed into an altogether


new form with only specific properties. There are two operators of this type.
I. Select: The operator projects values on basis of a transform function.
II. SelectMany: The operator project the sequences of values which are based on a
transform function as well as flattens them into a single sequence.
Ex: products.select(p->p.productName) Ex: products.selectMany(p->p.productType)

3.Partitioning Operators: These divide an input sequence into two separate sections
without rearranging the elements of the sequence and then returning one of them. There are four operators
of this type.
I. Skip: Skips some specified number of elements within a sequence and returns the remaining ones.
II. SkipWhile : Same as that of Skip with the only exception that number of elements
to skip are specified by a Boolean condition.
III. Take: Take a specified number of elements from a sequence and skip the
remaining ones.
IV. TakeWhile : Same as that of Take except the fact that number of elements to take
are specified by a Boolean condition.
Ex: products.take(500)
Ex: products.skip(4) Ex: products.takeWhile (Boolean b)
Ex: products.skipWhile(Boolean b)

Q. 11 Explain Conditional or Flow Control Statements in XML Tag Library with examples.

Conditional or Flow Control Statements Flow control XML actions explained below:
1. The <x:if> tag allows us to process the body content of the <x:if> tag if a condition evaluates to true and
consists of two variants, with or without a body.
The following code snippets shows the two variants of the <x:if> tag where the
square brackets indicate optional attributes and the curly bracers indicate a choice of options within them
where the default is underlined.
// Evaluate XPath expression and save test condition result to var
<x:if select="XPathExpression" var="varName"
[scope="[page request | session | application}"]/>
// Evaluate XPath expression and optionally save test condition result to var.
// Process body content if condition evaluates to true.
<x:if select="XPathExpression" [var="varName"]
[scope="[page request session application}"]>
body content to process
</x:if>

2.The <x:choose> tag is used in conjunction with the <x:when> and <x:otherwise> tags and works in a
similar way to the switch.. case.. default Java conditional. There are two variants of the <x:choose> tag as
shown in the code snippets below:
//<x:choose> and <x:when>
<x:choose>
<x:when select="XPathExpression"> expression evaluates to true
Page 10 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

</x:when>
<x:when select="XPathExpression"> expression evaluates to true
</x:when>
</x:choose>

// <x:choose> <x:when> and <x:otherwise>


<x:choose>
<x:when select="XPathExpression">
expression evaluates to true
</x:when>
<x:when select="XPathExpression">
expression evaluates to true
</x:when> <x:otherwise>
no expressions have evaluated to true
</x:otherwise>
</x:choose>
3. The <x:forEach> tag evaluates the given XPath expression and repeats its nested
body content over the result, setting the context node to each element in the iteration.
The following code snippet shows the syntax of the <x:forEach> tag where the square brackets indicate
optional attributes.
// Evaluates given XPath expression and iterate over body content
<x:forEach ["var="varName"] select="XPathExpression"
["varStatus="varStatusName"]["begin="begin"]["end="end"]["step="step"]>
body content
</x:forEach>

Q. 12 How to query and update data in JSTL?

1. JSTL Query Tag <sql:query> provides capability to fetch the data from databased by executing
query directly from JSP and it can be stored in a variable to use later with the help of scope
attribute.
Syntax:
<sql:query var"<string>" scope="<string>" sql="<string>" dataSource="<string> startRow="<string>"
maxRows="<string>"/>
Attributes:

Name Required Type Description


var True java.lang.String Name of the variable to store
the query result. This variable
is of
javax.servlet.jsp.jstl.sql.Result.
scope False java.lang.String Scope of the var to be placed
in.
sql False java.lang.String SQL query to execute.
dataSource False java.lang.String Datasource relative path in the
JNDI tree.
startRow False java.lang.String Starting index to show the
results. If specified, the results
from the index specified here
will be displayed.
maxRows False java.lang.String The maximum number of rows
to be fetched from the query.

Page 11 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Example:
<sql:setDataSource var="myDS" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"
user="root" password=""/>
<sql:query dataSource="${myDS]" var="citizens">
SELECT * from citizens;
</sql:query>
<table border="1">
<c:forEach var="row" items="${citizens.rows}">
<tr>
<td><c:out value="${row.ssn}"/></td>
<td><c:out value="${row.first_name}"/></td>
<td><c:out value="${row.last_name}"/></td>
<td><c:out value="${row.address}"/></td>
<td><c:out value="${row.telephone}"/></td>
</tr>
</c:forEach>
</table>

2. The <sql:update> tag executes the provided SQL query through its body or through its sql
attribute. JSTL Update Tag provides capability to write insert, update or delete statements
directly from JSP.
Syntax:
<sql:update var="<string>" scope="<string>" sql="<string>" dataSource="<string>"/>

Name Required Type Description


var False java.lang.String Name of the
variable which
stores the count of
the rows affected
after the query
execution.
scope False java.lang.String Scope for var to
store.
sql False java.lang.String SQL query to
execute
dataSource False java.lang.String Associated data
source of the
database

Example:
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/database_name"
var="localSource"
user="database_user"
password="database_password"/>
<sql:update dataSource="${snapshot}" var="count">
INSERT INTO Employees VALUES (333, 27, 'Anamika', 'Rajput');
</sql:update>
<sql:query dataSource="${localSource}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1" width="100%">
<tr>

Page 12 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="$(result.rows]">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first)"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>

Q. 13 What is EL? Explain immediate EL, deferred EL, LValue and RValue in detail.

Expression Language:
JSP Expression Language provides a way to simplify expressions. It is a
simple language used for accessing implicit objects. Java classes and for
manipulating collections in an elegant manner. It is the newly added
feature in JSP technology version 2.0.
The expression language also allows page authors to use simple
expressions to dynamically read data from JavaBean components.
Unified Expression Language allows usage of simple expressions to
perform the following tasks:
ata stored in JavaBeans components,
various data structures and implicit objects.

components.

Types of Evaluation Expressions:


Unified EL supports two types of evaluation expressions: Immediate and
Deferred evaluation
1. Immediate Evaluation:
Immediate evaluation means that the expression is evaluated and the result
returned as soon as the page is first rendered.
Syntax:
${<Expression>}
Here, Expression stands for valid expression.
The following example shows a tag whose value attribute references an
immediate evaluation expression that updates the quantity of books
retrieved from the backing bean named catalog:
<h:outputText value="${catalog.bookQuantity}" />
2. Deferred Evaluation:
Deferred evaluation means that the technology using the expression
language can use its own machinery to evaluate the expression sometime
later during the page’s lifecycle, whenever it is appropriate to do so.
Syntax:
#{<Expression>}
Here, Expression stands for valid expression.
Because of its multiphase lifecycle, JavaServer Faces technology uses
mostly deferred evaluation expressions. During the lifecycle, component
Page 13 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

events are handled, data is validated, and other tasks are performed in a
particular order. Therefore, a JavaServer Faces implementation must defer
evaluation of expressions until the appropriate point in the lifecycle.
Other technologies using the EL might have different reasons for using
deferred expressions.
The following example shows a JavaServer Faces h:inputText tag, which
represents a field component into which a user enters a value. The
h:inputText tag’s value attribute references a deferred evaluation
expression that points to the name property of the customer bean:
<h:inputText id="name" value="#{customer.name}" />
Value Expressions:
The unified EL provides two types of value expressions:

Can only read data, but cannot write data. Expressions that use deferred
valuation syntax are always rvalue expressions.

Can read and write data. Expressions that uses deferred evaluation syntax
can act as both Rvalue and Lvalue expressions.

Q. 14 Explain JSTL core Tag Library.

JSTL core Tag Library:


The Core Tag Library contains tags that are essential to nearly any Web application. Examples of
core tag libraries are looping, evaluation of expression and basic input and output.
The URI of the Core Tag Library is “http://java.sun.com/jsp/jstl/core” and prefix is c.
The syntax used for including JSTL Core tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
The Core Tag Library consists of four distinct functional sections:
A) General - Purpose Actions: These actions allow adding and removing variables ,displaying
variable values and enclosing a group of tags within a try-catch block.
1. <c:out>
The < c:out> tag displays the result of an expression. This is almost similar to the way <%= %>
works.
Example:
<c:out value = "${'Hello World‟}"/>
This will print Hello World as a response.
2. <c:set>
The <c:set> tag sets the result of an expression evaluation in a 'scope'.
Example:
<c:set var = "salary" scope = "session" value = "${2000}"/>
This will set a variable names session with the value 2000.
3.<c:remove >
The <c:remove > tag removes a scoped variable (from a particular scope, if specified).
Example:
<c:remove var = "salary"/>
This will remove the variable named salary.
4. <c:catch>
The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it.
Example:
<c:catch var ="catchException">
<% int x = 5/0;%>
</c:catch>
This code block will catch ArithmeticException.

Page 14 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

B) Conditional Actions Or Flow Control Statements: Conditional Actions are used for conditional
processing within a JSP page.
1. <c:if>
The <c:if> tag evaluates an expression and displays its body content only if the expression
evaluates to true.
Example:
<c:if test = "${salary > 20000}">
<p>My salary is: <c:out value = "${salary}"/><p>
</c:if>
This will print the statement within <c:if > tag if the condition mentioned in test evaluates to true.
2. <c:choose>,<c:when>,<c:otherwise>:
The <c:choose> works like a Java switch statement in that it lets you choose between a number of
alternatives. Where the switch statement has case statements, the tag <c:choose> has <c:when>
tags. Just as a switch statement has the default clause to specify a default action, <c:choose> has
<c:otherwise> as the default clause.
Example:
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than equal to number2"}
</c:when>
<c:otherwise>
<c:out value=" ${'number1 is largest number!'}"/>
</c:otherwise>
</c:choose>Example
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than equal to number2"}
</c:when>
<c:otherwise>
<c:out value=" ${'number1 is largest number!'}"/>
</c:otherwise>
</c:choose>

C) Iterator Actions:
Iterator Actions simplify iteration through collection of objects.
1. <c:forEach >
The <c:forEach> tag is a commonly used tag because it repeats the nested
body content for fixed number of times or over collection.
Example
<c:forEach var = "i" begin = "1" end = "5">
Item <c:out value = "${i}"/><p>
</c:forEach>

Page 15 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

This will print the values from 1 to 5.


2. <c:forTokens>
The <c:forTokens> tag iterates over tokens which is separated by the
supplied delimeters. It is used for break a string into tokens and iterate
through each of the tokens to generate output.
This tag has similar attributes as <c:forEach> tag except one additional
attributes delims which is used for specifying the characters to be used as
delimiters.
Example
<c:forTokens items=”Chris-Steve-Liza" delims="-" var="name">
<c:out value="${name}"/><p>
</c:forTokens>
This will print the names as separate tokens.

D) Url Related Actions:


These actions are used to import resources, redirect HTTP responses ,create URLs or encode a
request of parameters.
1. <c:redirect>
The < c:redirect > tag redirects the browser to a new URL.
Example:
<c:redirect url="http://abc.com"/>
This will redirect to abc.com
2. <c:url>
The < c:url > tag creates a URL with optional query parameter. It is used
for url encoding or url formatting. This tag automatically performs the
URL rewriting operation.
Example:
<c:url value="/Register.jsp"/>
3. <c:param>
The < c:param > tag add the parameter in a containing 'import' tag's URL.
Example:
<c:url value="/index.jsp" var="completeURL"/>
<c:param name="user" value="Ann"/>

Q. 15 Explain the various scope of JSP application.

SCOPE OF JSP OBJECTS:


The availability of a JSP object for use from a particular place of the
application is defined as the scope of that JSP object. Every object created
in a JSP page will have a scope. Object scope in JSP is segregated into
four parts and they are page, request, session and application.
1. Page Scope:
Objects with page scope are accessible only within the page in which
they're created. The data is valid only during the processing of the current
response; once the response is sent back to the browser, the data is no
longer valid. If the request is forwarded to another page or the browser
makes another request as a result of a redirect, the data is also lost.
//Example of JSP Page Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="page" />
2. Request Scope:
Objects with request scope are accessible from pages processing the same
request in which they were created. Once the container has processed the
request, the data is released. Even if the request is forwarded to another
Page 16 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

page, the data is still available though not if a redirect is required.


//Example of JSP Request Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="request" />
3. Session Scope:
Objects with session scope are accessible from pages processing requests
that are in the same session as the one in which they were created. A
session is the time users spend using the application, which ends when they close their browser,
when they go to another Web site, or when the
application designer wants (after a logout, for instance). So, for example,
when users log in, their username could be stored in the session and
displayed on every page they access. This data lasts until they leave the
Web site or log out.
//Example of JSP Session Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="session" />
4. Application Scope:
Objects with application scope are accessible from JSP pages that reside in
the same application. This creates a global object that's available to all
pages.
Application scope uses a single namespace, which means all your pages
should be careful not to duplicate the names of application scope objects
or change the values when they're likely to be read by another page (this is
called thread safety). Application scope variables are typically created and
populated when an application starts and then used as read-only for the
rest of the application.
//Example of JSP Application Scope
<jsp:useBean id="employee" class="EmployeeBean" scope="application" />

Q. 16 Develop a simple JSP application to accept values from html page and display on next page.
(Name-txt, age-txt, hobbies-checkbox, email-txt, gender-radio button).

HTML Form :
<Html>
<form action="Show.jsp" >
<br> Enter Name <input type=text name=txtName >
<br> Enter Age <input type=text name=txtAge >
<br> Select Hobbies <input type=checkbox name=txtHob value=Reading >Reading
<input type=checkbox name=txtHob value=Singing >Singing
<br> Select Gender <input type=radio name=txtGender value=Male >Male
<input type=radio name=txtGender value=Female >Female
<input type=radio name=txtGender value=Other >Other
<input type=submit>
</form>
</HTML>
JSP Code :
Your Name <%=request.getParameter("txtName") %>
Your Age <%=request.getParameter("txtAge") %>
<%
foreach(i in request.getParameters("txtHob")) out.println("<br>"+i);
%>
Gender Selected <%=request.getParameter("txtGender") %>

Page 17 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

Q. 17 Explain the <jsp:useBean > tag with its attribute. Support your answer with suitable code
snippet.

<jsp:useBean > tag:


The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is
already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it
instantiates the bean.
Syntax of jsp:useBean action tag:
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or application. The default
scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope is page.
o request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same application.
It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have
no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Simple example of jsp:useBean action tag

In this example, we are simply invoking the method of the Bean class.

For the example of setProperty, getProperty and useBean tags, visit next page.
Calculator.java (a simple Bean class)
1. package com.javatpoint;
2. public class Calculator{
3.
4. public int cube(int n){return n*n*n;}
5.
6. }
index.jsp file
1. <jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
2.
3. <%
Page 18 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 3

4. int m=obj.cube(5);
5. out.print("cube of 5 is "+m);
6. %>

Q. 18 What is wrong in using JSP scriptlet tag? How JSTL fixes JSP scriptlet shortcomings?

The scriptlet tags provided by JSP technology should not be used to embed your business logic and
then rendering the view. This is because of the following disadvantages:

1. No Code Reusability: Using the scriplet tags on JSP reduces the code reusability as if done so
than view will be binded to that scriplet tags.
2. Poor structure of JSP page: Scriptlet tags if used on JSP page for view management does result
in a structure of code that is difficult to understand and interpret.
3. Reduced readability of html code: Understanding the HTML of the final view
4. Increases efforts to understand the JSP: Because view is dependent conditions defined in the
scriplet tags, it do takes time to understand the JSP.
5. Prone to exception and hence no view at all: If any exception occurs on the JSP because of
business logic, there will be no view at all.

How JSTL fixes JSP Scriptlet's shortcomings? (Advantages of JSTL over JSP)
1. Scriptlets (Java codes within JSP) are complex and are extremely hard to be maintained. Unlike
scriptlets, JSTL makes our JSP readable and maintainable.
2. HTML programmer may find it hard to modify the JSP with the scriptlets as he or she may not have
the Java programming knowledge. However, if we are using JSTL to replace our scriptlets, HTML
programmer can easily understand on what's going on in the JSP as JSTL is in the form of XML tags
similar to the normal HTML tags.
3. JSTL requires less code compared to scriptlets.
4. Standard Tag: It provides a rich layer of the portable functionality of JSP pages. It's easy for a
developer to understand the code.
5. The name of each tag in JSTL is self-explanatory and is easy to understand.
6. Automatic Java beans Introspection Support: It has an advantage of JSTL over JSP scriptlets.
JSTL Expression language handles JavaBean code very easily. We don't need to downcast the
objects, which has been retrieved as scoped attributes. Using JSP scriptlets code will be
complicated, and JSTL has simplified that purpose.
7. Easier for humans to read : JSTL is based on XML, which is very similar to HTML
Hence, it is easy for the developers to understand.
8. Easier for computers to understand: Tools such as Dreamweaver and front page are generating
more and more HTML code. HTML tools do a great job of formatting HTML code. The HTML code is
mixed with the scriplet code. As JSTL is expressed as XML compliant tags, it is easy for HTML
generation to parse the JSTL code within the document.
9. Fast Development JSTL provides many tags that simplifies the JSP.

Page 19 of 19
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
www.acuityeducare.com

Acuity Educare

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 4

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q.1 Write a short note on EJB architecture.

EJB Architecture:
The Enterprise JavaBeans (EJB) component architecture is designed to enable enterprises to build
scalable, secure, multiplatform, businesscritical applications as reusable, server-side components.
EJB architecture is at the heart of the Java 2 platform, Enterprise Edition (J2EE).
With the growth of the Web and the Internet, more and more enterprise applications are now Web
based, including both intranet and extranet applications.

Together, the J2EE and EJB architectures provide superior support for Web-based enterprise
applications.
EJB architecture is composed of:
1. Enterprise bean server
2. Enterprise bean container
3. Enterprise bean
4. Enterprise bean clients
1. Enterprise Bean Server:
An EJB server is a component transaction server.
It supports the EJB server side component model for developing and deploying
distributed enterprise level applications in multi-tiered environment.
The key responsibilities of an Application Server are:
• Management API
• Process and thread management
• Database connection pooling and caching
• System Resources management
2. Enterprise Bean Container:
The EJB container is one of the logical constructs which makes up the Full Java EE profile.
An EJB container manages the enterprise beans contained within it.
EJB server provides one or more containers. From our architecture diagram, we saw that the
EJB container construct is the second outmost construct of the architecture.
Furthermore, its key responsibilities are:
• It provides a runtime environment for Enterprise Java Beans
• It provides persistence management
• It is responsible for the Lifecycle management of EJBs
• It is in charge of ensuring that all EJBs are secured.
3. Enterprise Bean:
Enterprise Beans are reusable modules code that combine related tasks into well-defined interface.
These enterprise bean EJB components contain the methods that execute business login and
access data sources.
Business component developed using EJB architecture are called as Enterprise Beans. EJBS are
server-side components for encapsulating application's business logic.
Page 1 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

An EJB can offer specific enterprise service either alone or in conjunction with other EJBs.
4. Enterprise Bean Clients:
There are two types of client view:
• Remote Client View • Local Client View
1. Remote Client View:
i. The remote client view specification became available beginning with EJB.
ii. The remote client view of an enterprise bean is location independent.
iii. A client running in the same JVM as a bean instance uses the same API to access the
bean as a client running in a different JVM on the same or different machine.
iv. Remote interface: The remote interface specifies the remote business methods that a
client can call on an enterprise bean.
v. Remote home interface: The remote home interface specifies the methods used by
remote clients for locating, creating, and removing instances of enterprise bean classes.
2. Local Client View:
i. Unlike the remote client view, the local client view of a bean is location dependent.
ii. Local client view access to an enterprise bean requires both the local client and the
enterprise bean that provides the local client view to be in the same JVM.
iii. The local client view therefore does not provide the location transparency provided by
the remote client view.
iv. Local interfaces and local home interfaces provide support for lightweight access from
enterprise bean that are local clients.
v. Session and entity beans can be tightly couple with their clients, allowing access without
the overhead typically associated with remote method calls.
vi. The local client view specification is available in EJB 2.0 or later.
vii. Local interface:
The local interface is a lightweight version of the remote interface, but for local clients.
viii. It includes business logic methods that can be called by a local client.
ix. Local home interface:
The local home interface specifies the methods used by local clients for locating, creating,
and removing instances of enterprise bean classes.

Q. 2 What are the various features provided by EJB?

• Interoperability: EJB architecture is mapped to standard CORBA.EJB make it work with


components developed in different language like VC++ and CORBA. The EJB client view interface
serves as well-defined integration point between components built using different programming
languages.
• One business logic having many presentation logic: EJB performs a separation between business
logic and presentation logic. This separation makes it possible to develop multiple presentation logic
for the same business process.
• Complete Focus only on Business Logic: This allows the server vendor to concentrate on system
level functionalities, while the developer can concentrate more on only the business logic for the
domain specific applications. Developer need not code for these hardcore services. The results of
application get more quickly.
• Server-Side Write Once, Run Anywhere: EJB uses java language which is portable across multiple
platforms. They can be developed once and then deployed multiple platforms without recompilation
or source code modification.
• EJB provides Distributed Transaction support: EJB provides transparency for distributed
transactions. This means that a client can begin a transaction and then invoke methods on Beans
present within two different servers, running on different machines, platforms or JVM.
• It provides of vendor specific enhancements: Since the EJB specification provides a lot of flexibility
for the vendors to create their own enhancements, the EJB environment may end being feature rich.
Page 2 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 3 What are types of enterprise bean?

Types of Enterprise Java Bean:


The EJB 2.0 specification defines three types of Enterprise JavaBeans: the session bean, the entity bean,
and the message-driven bean.

Session beans contain business-processing logic. Entity beans contain data-processing logic. Message-
driven beans allow clients to asynchronously invoke business logic.
1. Session Bean:
 Session beans are Java beans which encapsulate the business logic in a centralized and
reusable manner such that it can be used by a number of clients.
 A session bean objects are short-lived.
 Are not persistent in a database.
 They can be stateful or stateless.
 Execute for a single client.
 Can be transaction aware.
 Session beans implement a conversation between a client and the server side. Session
beans execute a particular business task on behalf of a single client during a single session.
 They implement business logic such as workflow, algorithms, and business rules.
 Session beans are analogous to interactive sessions. Just as an interactive session isn’t
shared among users, a session bean is not shared among clients.
 Like an interactive session, a session bean isn’t persistent (that is, its data isn’t saved to a
database). Session beans are removed when the EJB container is shut down or crashes.
 Session beans typically contain business process logic and workflow, such as sending an
email, looking up a stock price from a database, and implementing compression and
encryption algorithms.
 There are 3 types of Session beans:
 Stateless
 Stateful
 Singleton
i. Stateless Session Beans: A stateless session bean, by comparison, does not
maintain any conversational state. Stateless session beans are pooled by their
container to handle multiple requests from multiple clients.
ii. Stateful Session Beans: A stateful session bean acts on behalf of a single client and
maintains client-specific session information(called conversational state) across
multiple method calls and transactions. It exists for the duration of a single
client/server session.
iii. Singleton Session Beans: Provide shared data to client and components within an
access application and are instantiated only once per application.

Page 3 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

2. Entity Beans:
 Entity beans are persistent objects.
 They typically represent business entities, such as customers, products, accounts, and
orders.
 Typically, each entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.
 The state of an entity bean is persistent, transactional, and shared among different clients.
 It hides complexity behind the bean and container common services. Because the clients
might want to change the same data, it’s important that entity beans work within
transactions.
 Entity beans typically contain data-related logic, such as inserting, updating, and removing a
customer record in the database.
 Two types of entity beans are :
a. container-managed persistence (CMP)
b. bean-managed persistence
a. Container-managed persistence:
In a CMP entity bean, the EJB container manages the bean’s persistence according to the
data-object mapping in the deployment descriptor.
Any change in the entity bean’s state will be automatically saved to the database by the
container.
No code is required in the bean to reflect these changes or to manage the database
connection.
b. Bean-managed persistence:
A BMP entity bean has to manage both the database connections and all the changes to the
bean’s state.(Entity bean that manage their own persistence are called BMP entity bean.)
3. Message Driven Beans:
 Message-driven beans are enterprise beans that receive and process JMS messages.
Unlike session or entity beans, message-driven beans have no interfaces.
 They can be accessed only through messaging and they do not maintain any conversational
state.
 Message-driven beans allow asynchronous communication between the queue and the
listener, and provide separation between message processing and business logic.
 Message driven beans are:
 Do not have home and component interface.
 Do not have business methods but define message listener method which the EJB container
invokes to deliver messages.
 Do not hold any state between calls of the message listener method.
 Are relatively short-lived.
 Can be Transaction aware.
 Do not represent directly shared data in the database, but they can access and update this
data. In synchronous communication, the client blocks until the server-side object completes
processing.
 In asynchronous communication, the client sends its message and does not need to wait for
the receiver to receive or process the message.
 Session and entity beans process messages synchronously. Message-driven beans, on the
other hand, are stateless components that are asynchronously invoked by the container as a
result of the arrival of a Java Message Service (JMS) message.
 A message-driven bean receives a message from a JMS destination, such as a queue or
topic, and performs business logic based on the message contents, such as logic to receive
and process a client notification.
Page 4 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 6 What are types of session beans?

Types of Session Beans:


Session beans are of three types: stateful, stateless, and singleton.
1. Stateful Session Beans:
 The state of an object consists of the values of its instance variables. In a stateful session
bean, the instance variables represent the state of a unique client/bean session.
 Because the client interacts (“talks”) with its bean, this state is often called the
conversational state. As its name suggests, a session bean is similar to an interactive
session.
 A session bean is not shared; it can have only one client, in the same way that an interactive
session can have only one user.
 When the client terminates, its session bean appears to terminate and is no longer
associated with the client.
 The state is retained for the duration of the client/bean session. If the client removes the
bean, the session ends and the state disappears.
 This transient nature of the state is not a problem, however, because when the conversation
between the client and the bean ends, there is no need to retain the state.
2. Stateless Session Beans:
A stateless session bean does not maintain a conversational state with the client.
 When a client invokes the methods of a stateless bean, the bean’s instance variables may
contain a state specific to that client but only for the duration of the invocation.
 When the method is finished, the clientspecific state should not be retained. Clients may,
however, change the state of instance variables in pooled stateless beans, and this state is
held over to the next invocation of the pooled stateless bean.
 Except during method invocation, all instances of a stateless bean are equivalent, allowing
the EJB container to assign an instance to any client.
 That is, the state of a stateless session bean should apply across all clients. Because they
can support multiple clients, stateless session beans can offer better scalability for
applications that require large numbers of clients.
 Typically, an application requires fewer stateless session beans than stateful session beans
to support the same number of clients.
 A stateless session bean can implement a web service, but a stateful session bean cannot.
3. Singleton Session Beans:
 A singleton session bean is instantiated once per application and exists for the lifecycle of
the application.
 Singleton session beans are designed for circumstances in which a single enterprise bean
instance is shared across and concurrently accessed by clients.
 Singleton session beans offer similar functionality to stateless session beans but differ from
them in that there is only one singleton session bean per application, as opposed to a pool of
stateless session beans, any of which may respond to a client request.
 Like stateless session beans, singleton session beans can implement web service
endpoints.
 Singleton session beans maintain their state between client invocations but are not required
to maintain their state across server crashes or shutdowns.
 Applications that use a singleton session bean may specify that the singleton should be
instantiated upon application startup, which allows the singleton to perform initialization tasks
for the application.

Page 5 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

 The singleton may perform cleanup tasks on application shutdown as well, because the
singleton will operate throughout the lifecycle of the application.
Q. 5 Explain the life cycle of stateful and stateless session beans.

Stateful Session Bean:

1. Create
2. Dependency Injection, if any
3. PostConstruct callback, if any
4. Init method or ejbCreate<Method>, if any

1. Remove
2 PreDestroy callback, if any
The client initiates the lifecycle by obtaining a reference to a stateful session bean. The container
performs any dependency injection and then invokes the method annotated with @PostConstruct, if
any. The bean is now ready to have its business methods invoked by the client.
While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by
moving it from memory to secondary storage. The EJB container invokes the method annotated
@PrePassivate, if any, immediately before passivating it. If a client invokes a business method on the
bean while it is in the passive stage, the EJB container activates the bean, calls the method annotated
@PostActivate, if any, and then moves it to the ready stage. At the end of the lifecycle, the client
invokes a method annotated @Remove, and the EJB container calls the method annotated
@PreDestroy, if any. The bean's instance is then ready for garbage collection.
Your code controls the invocation of only one lifecycle method, the method annotated @Remove. All
other methods are invoked by the EJB container.

Q. 6 Explain life cycle of message driven beans.

The EJB container usually creates a pool of message-driven bean instances.


For each instance, the EJB container performs these tasks.
1. If the message-driven bean uses dependency injection, the container injects these references
before instantiating the instance.
2. The container calls the method annotated @PostConstruct, if any.
Like a stateless session bean, a message-driven bean is never passivated and has only two states:
nonexistent and ready to receive messages.
At the end of the lifecycle, the container calls the method annotated @PreDestroy, if any.
The bean’s instance is then ready for garbage collection.

Page 6 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 7 What is Message Driven Bean? Explain its usage

 A message driven bean (MDB) is a bean that contains business logic.


 But, it is invoked by passing the message. So, it is like JMS Receiver. MDB asynchronously
receives the message and processes it.
 A message driven bean receives message from queue or topic, so you must have the knowledge of
JMS API.
 A message-driven bean is an enterprise bean that allows Java EE applications to process
messages asynchronously.
 This type of bean normally acts as a JMS message listener, which is similar to an event listener but
receives JMS messages instead of events.
 The messages can be sent by any Java EE component (an application client, another enterprise
bean, or a web component) or by a JMS application or system that does not use Java EE
technology. Message-driven beans can process JMS messages or

Q. 8 Define and explain Interceptors

Defining an Interceptor:

1. An interceptor method may be defined on an enterprise bean class or on an interceptor class


associated with the bean. An interceptor class is a class which is distinct from the bean class itself
and whose methods are invoked in response to business method invocations and/or lifecycle events
on the bean.
2. Any number of interceptor classes may be defined for a bean class. It is possible to carry state
across multiple interceptor method invocations for a single business method invocation or lifecycle
callback event for a bean in the context data of the InvocationContext object.
3. An interceptor class must have a public no-arg constructor. The programming restrictions that apply
to enterprise bean components apply to interceptors as well. Interceptor methods and interceptor
classes are defined for a bean by means of metadata annotations or the deployment descriptor.
4. When annotations are used, one or more interceptor classes are denoted using the Interceptors
annotation on the bean class self and/or on business methods of the bean. If multiple interceptors
are defined, the order in which they are invoked is determined by the order in which they are
specified in the Interceptors annotation.

Page 7 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

5. Interceptors can be defined in Java as a method interceptor or a class interceptor. The preferred
way to define in Java code is by using meta-data annotations. They can be defined in the
application descriptor as well, but, in that case they are not portable across java EE servers. Some
of the meta-data annotations found in the javax.interceptor package are: @AroundInvoke,
@AroundTimeout, @PostConstruct and @PreDestroy.
6. An AroundInvoke method can be defined on:
• Enterprise Bean Class
• Interceptor class (Normal Java class without any inheritance.

Q. 6 What is Naming service? Explain with the help of a diagram.

 The Java Naming and Directory Interface (JNDI) is an application programming interface (API) for
accessing different kinds of naming and directory services.
 JNDI is not specific to a particular naming or directory service, it can be used to access many
different kinds of systems including file systems; distributed objects systems like CORBA, Java RMI,
and EJB; and directory services like LDAP, Novell NetWare, and NIS+.
 JNDI is similar to JDBC in that they are both Object-Oriented Java APIs that provide a common
abstraction for accessing services from different vendors.
 While JDBC can be used to access a variety of relational databases, JNDI can be used to access a
variety of of naming and directory services.
 Using one API to access many different brands of a service is possible because both JDBC and
JNDI subscribe to the same architectural tenet: Define a common abstraction that most vendors can
implement.
 The common abstraction is the API. It provides an objectified view of a service while hiding the
details specific to any brand of service.
 The implementation is provided by the vendor, it plugs into the API and implements code specific to
accessing that vendor's product.

The JNDI architecture consists of an API and a service provider interface (SPI). Java applications
use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of
naming and directory services to be plugged in transparently, thereby allowing the Java application
using the JNDI API to access their services.

Page 8 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 10 Write short note on Enterprise Bean Server and Enterprise Bean.

EJB Architecture: The Enterprise JavaBeans (EJB) component architecture is designed to enable
enterprises to build scalable, secure, multiplatform, businesscritical applications as reusable, server-
side components. EJB architecture is at the heart of the Java 2 platform, Enterprise Edition (J2EE).
With the growth of the Web and the Internet, more and more enterprise applications are now Web
based, including both intranet and extranet applications.
Together, the J2EE and EJB architectures provide superior support for Web-based enterprise
applications.
EJB architecture is composed of:
1 Enterprise bean server
2 Enterprise bean container
3 Enterprise bean
4 Enterprise bean clients
Enterprise Bean Server:
An EJB server is a component transaction server. It supports the EJB server side component
model for developing and deploying distributed enterprise level applications in multi-tiered
environment. The key responsibilities of an Application Server are:
• Management API
• Process and thread management
• Database connection pooling and caching
• System Resources management
Enterprise Bean:
Enterprise Beans are reusable modules code that combine related tasks into well-defined interface.
These enterprise bean EJB components contain the methods that execute business login and
access data sources. Business component developed using EJB architecture are called as
Enterprise Beans.
EJBS are server-side components for encapsulating application's business logic. An EJB can offer
specific enterprise service either alone or in conjunction with other EJBs.

Q. 11 Describe Packaging of Enterprise Beans in JAR and WAR Modules.

Enterprise Beans in JAR Modules:


An EJB JAR file is portable and can be used for various applications. To assemble a Java EE
application, package one or more modules, such as EJB JAR files, into an EAR file, the archive file
that holds the application. When deploying the EAR file that contains the enterprise bean's EJB JAR
file, you also deploy the enterprise bean to the Glassfish Server. You can also deploy an EJB JAR
that is not contained in an EAR file. Following figure shows the contents of an EJB JAR file.
WAR Modules:
Enterprise beans often provide the business logic of a web application. In these cases, packaging
the enterprise bean within the web application's WAR module simplifies deployment and application
organization. Enterprise beans may be packaged within a WAR module as Java programming
language class files or within a JAR file that is bundled within the WAR module.
To include enterprise bean class files in a WAR module, the class files should be in the WEB-
INF/classes directory.
To include a JAR file that contains enterprise beans in a WAR module, add the JAR to the WEB-
INF/lib directory of the WAR module.
WAR modules that contain enterprise beans do not require an ejb-jar.xml deployment descriptor. If
the application uses ejb-jar.xml, it must be located in the WAR module's WEB-INF directory.
For example, suppose that a web application consists of a shopping cart enterprise Jean a credit
card processing enterprise bean, and a Java servlet front end. The shopping cart bean exposes a
local, no-interface view and is defined as follows:
package com.example.cart;
@Stateless

Page 9 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

public class CartBean {...}


The credit card processing bean is packaged within its own JAR file, cc.jar, exposes a cal, no-
interface view, and is defined as follows:
package com.example.cc;
@Stateless
public class CreditCardBean (...)

The servlet, com.example.web.StoreServlet, handles the web front end and uses both Cart Bean and
CreditCardBean. The WAR module layout for this application looks as follows:
WEB-INF/classes/com/example/cart/CartBean.class WEB-
INF/classes/com/example/web/StoreServlet
WEB-INF/lib/cc.jar
WEB-INF/ejb-jar.xml
WEB-INF/web.xml

Q. 12 How to access No-Interface View and Local Business Interface?

Accessing No-Interface View:


Client access to an enterprise bean that exposes a local, no-interface view is accomplished through
either dependency injection or JNDI lookup.
1.Client Access Using Dependency Injection : To obtain a reference to the no-interface view of an
enterprise bean through dependency injection, use the javax.ejb.EJB annotation and specify the
enterprise bean's implementation class:
@EJB
ExampleBean exampleBean;
2.Client Access Using JNDI LookUp: To obtain a reference to the no-interface view of an enterprise
bean through JNDI lookup, use the javax.naming.InitialContext interface's lookup method:
ExampleBean exampleBean = (ExampleBean)
InitialContext.lookup("java:module/ExampleBean");

Accessing Local Business Interface:


Client access to enterprise beans that implement local business interfaces is accomplished through
either dependency injection or JNDI lookup.
1. Client Access Using Dependency Injection: To obtain a reference to the local business interface of an
enterprise bean through dependency injection, use the javax.ejb.EJB annotation and specify the
enterprise bean's local business interface name:
@EJB
Example example;
2.Client Access Using JNDI LookUp: To obtain a reference to a local business interface of an enterprise
bean through JNDI lookup, use the javax.naming.InitialContext interface's lookup method:
ExampleLocal example = (ExampleLocal)
InitialContext.lookup("java:module/ExampleLocal");

Q. 13 Write short note on Lifecycle of a Message Driven Bean with onMessage( ) Method.

The EJB container usually creates a pool of message-driven bean instances. For each instance, the
EJB container performs these tasks. 1. If the message-driven bean uses dependency injection, the
container injects these references before instantiating the instance. 2. The container calls the method
annotated @PostConstruct, if any. Like a stateless session bean, a message-driven bean is never
passivated and has only two states: nonexistent and ready to receive messages. At the end of the
lifecycle, the container calls the method annotated @PreDestroy, if any. The bean’s instance is then
ready for garbage collection

Page 10 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 14 How to define Interceptor? What is the role of AroundInvoke Method?

Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke
interceptor methods on an associated target class, in conjunction with method invocations or lifecycle
events. Common uses of interceptors are logging, auditing, and profiling. An interceptor can be
defined within a target class as an interceptor method, or in an associated class called an interceptor
class. Interceptor classes contain methods that are invoked in conjunction with the methods or
lifecycle events of the target class. Interceptor classes and methods are defined using metadata
annotations, or in the deployment descriptor of the application containing the interceptors and target
classes.
AroundInvoke:
The interceptor example demonstrates how to use an interceptor class, containing an
@AroundInvoke interceptor method, with a stateless session bean.
The HelloBean stateless session bean is a simple enterprise bean with two business methods,
getName and setName, to retrieve and modify a string. The setName business method has an
@Interceptors annotation that specifies an interceptor class, HelloInterceptor, for that method.
@Interceptors(HelloInterceptor.class)
public void setName(String name) {
this.name = name;
}
The HelloInterceptor class defines an @AroundInvoke interceptor method, modifyGreeting, that
converts the string passed to HelloBean.setName to lowercase.
@AroundInvoke
public Object modifyGreeting(InvocationContext ctx) throws Exception {
Object[] parameters = ctx.getParameters();
String param = (String) parameters[0];
param = param.toLowerCase();
parameters[0] = param;
ctx.setParameters(parameters);
try {
return ctx.proceed();
} catch (Exception e) { logger.warning("Error calling ctx.proceed in modifyGreeting()");
return null;
}
}

Page 11 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 15 What is DataSource Resource Definition in Java EE?

DataSource resources are used to define a set of properties required to identify and access a
database through the JDBC API. These properties include information such as the URL of the
database server, the name of the database, and the network protocol to use to communicate with the
server. DataSource objects are registered with the Java Naming and Directory Interface (JNDI)
naming service so that applications can use the JNDI API to access a DataSource object to make a
connection with a database.

Java EE 7 provides the option to programmatically define DataSource resources for a more flexible
and portable method of database connectivity.

The name element uniquely identifies a DataSource and is registered with JNDI. The value specified
in the name element begins with a namespace scope. Java EE 7 includes the following scopes:
 java:comp: Names in this namespace have per-component visibility.
 java:module: Names in this namespace are shared by all components in a module, for
example, the EJB components defined in an a ejb-jar.xml file.
 java:app: Names in this namespace are shared by all components and modules in an
application, for example, the application-client, web, and EJB components in an .EAR file.
 java:global : Names in this namespace are shared by all the applications in the server.

Q. 16 What is Java Naming and Directory Interface? Explain.

The Java Naming and Directory Interface (JNDI) is an application programming interface (API) that
provides naming and directory functionality to applications written using the Java programming
language. It is defined to be independent of any specific directory service implementation. Thus a
variety of directories, new, emerging, and already deployed can be accessed in a common way.
Enterprise level applications use a lot of different directory services-lookup services that locate
resources associated with a particular name.

JNDI enables Java platform based applications to access multiple naming and directory services. Part
of the Java Enterprise application programming interface (API) set, JNDI makes it possible for
developers to create portable applications that are enabled for a number of different naming and
directory services, including: file systems; directory services such as Lightweight Directory Access
Protocol (LDAP), Novell Directory Services, and Network Information System (NIS); and distributed
object systems such as the Common Object Request Broker Architecture (CORBA), Java Remote
Method Invocation (RMI), and Enterprise JavaBeans (EJB).

Q. 17 Explain about enterprise bean container.

The EJB container is one of the logical constructs which makes up the Full Java EE profile. An EJB
container manages the enterprise beans contained within it. EJB server provides one or more
containers. From our architecture diagram, we saw that the EJB container construct is the second
outmost construct of the architecture. Furthermore, its key responsibilities are:
• It provides a runtime environment for Enterprise Java Beans
• It provides persistence management
• It is responsible for the Lifecycle management of EJBs
• It is in charge of ensuring that all EJBs are secured

Page 12 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Q. 18 Explain the working behind message driven bean.

Message-driven beans are enterprise beans that receive and process JMS messages. Unlike
session or entity heans, message-driven be ans have no interfaces. They can be accessed only
through messaging and they do not maintain any conversational state.
Message-driven beans allow asynchronous communication between the queue and the listener, and
provide separation between message processing and business logic. Message driven beans are:
 Do not have home and component interface.
 Do not have business methods but define message listener method which the EJB container
invokes to deliver messages.
 Do not hold any state between calls of the message listener method.
 Are relatively short-lived.
 Can be Transaction aware.
 Do not represent directly shared data in the database, but they can access and update this data.
In synchronous communication, the client blocks until the server-side object completes processing. In
asynchronous communication, the client sends its message and does not need to wait for the receiver
to receive or process the message. Session and entity beans process messages synchronously.
Message-driven beans, on the other hand, are stateless components that are asynchronously invoked
by the container as a result of the arrival of a Java Message Service (JMS) message. A message-
driven bean receives a message from a JMS destination, such as a queue or topic, and performs
business logic based on the message contents, such as logic to receive and process a client
notification.
An example of a message-driven bean is when a shopper makes an online purchase order; an order
bean could notify a credit verification bean. A credit verification bean could check the shopper’s
credit card in the background and send a notification message for approval. Because this notification
is asynchronous, the shopper doesn’t have to wait for the background processing to complete.

Q. 19 Explain basic look up in JNDI. Also explain resource injection in JNDI.

Basic look up in JNDI:


JNDI organizes its names into a hierarchy. A name can be any string such a
"com.mypack.ejb.TBean". A name can also be an object that implements the Name interface;
however a string is the most common way to name an object. A name is bound to an object in the
directory by storing either the object or a reference to the object in the directory service identified by
the name.
The Context class is the core of the JNDI API. You use it to perform any lookup and to add any new
name-value associations. When you use JNDI, you typically create an Initial Context object first:
Context ctx = new InitialContext();
The InitialContext constructor looks for a system property called java.naming.factory. The initial that
contains the name of the class that creates the InitialContext. Sometimes, you must supply this value
yourself. Some EJB containers, like the one that comes with Sun's J2EE SDK, already have this
property set.

To look up an object from the naming service, use Context.lookup() and pass it the name of the
object that you want to retrieve. Suppose that there is an object in the naming service with the name
cn=Rosanna Lee, ou-People. To retrieve the object, you would write
Object obj = ctx.lookup("cn=Yeshu Sambare, ou=People");
The type of object that is returned by lookup() depends both on the underlying naming system and
on the data associated with the object itself. A naming system can contain many different types of
objects, and a lookup of an object in different parts of the system might yield objects of different
types. In this example, "cn=Yeshu Sambare, ou-People" happens to be bound to a context object
(javax.naming.ldap.LdapContext). You can cast the result of lookup() to its target class.
The three JNDI lookups are 1) java:global 2) java:module, and 3)java:app.
Page 13 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 4

Resource Injection:
The javax.annotation. Resource annotation is used to declare a reference to a resource; @Resource
can decorate a class, a field, or a method. The container will inject the resource referred to by
@Resource into the component either at runtime or when the component is initialized, depending on
whether field/method injection or class injection is used. With field-based and method-based
injection, the container will inject the resource when the application is initialized. For class-based
injection, the resource is looked up by The application at runtime.
The @Resource annotation has the following elements:
 name: The JNDI name of the resource.
 type: The Java language type of the resource.
 authenticationType: The authentication type to use for the resource.
 shareable: Indicates whether the resource can be shared.
 mappedName: A nonportable, implementation-specific name to which resource should be
mapped.
 description: The description of the resource.

Q. 20 Explain the life cycle of an interceptor.

Life Cycle of Interceptor:


 The lifecycle of an interceptor instance is the same as that of the bean instance with which it is
associated. When the bean instance is created, interceptor instances are created for each
interceptor class defined for the bean. These interceptor instances are destroyed when the bean
instance is removed. In the case of interceptors associated with stateful session beans, the
interceptor instances are passivated upon bean instance passivation, and activated when the bean
instance is activated.
 Both the interceptor instance and the bean instance are created or activated before any of the
respective PostConstruct or PostActivate callbacks are invoked. Any PreDestroy and PrePassivate
callbacks are invoked before the respective destruction or passivation of either the bean instance or
interceptor instance.
 An interceptor instance may hold state. An interceptor instance may be the target of dependency
injection. Dependency injection is performed when the interceptor instance is created, using the
naming context of the associated enterprise bean.
 The PostConstruct interceptor callback method is invoked after this dependency injection has taken
place on both the interceptor instances and the bean instance. Interceptors can invoke JNDI, JDBC,
JMS, other enterprise beans, and the EntityManager.
 The interceptors for a bean share the enterprise naming context of the bean for whose methods and
lifecycle events they are invoked. Annotations and/or XML deployment descriptor elements for
dependency injection or for direct JNDI lookup refer to this shared naming context.
 The EJBContext object may be injected into an interceptor class. The interceptor may use the
lookup method of the EJBContext interface to access the bean's JNDI naming context.
 The use of an extended persistence context is only supported for interceptors that are associated
with stateful session beans.

Page 14 of 14
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
www.acuityeducare.com

Acuity Educare

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 5

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

Q.1 What is Persistence? Explain with an example.

Persistence is one of the fundamental concepts of application development. It allows DATA to outlive
the execution of an application that created it. It is one of the most vital pieces of an application
without which all the data is simply lost. Majority of applications use persistent data. For example, GUI
applications need to store user preferences across program invocations, Web applications track user
movements and orders over long periods of time. Hence, it is imperative to choose an appropriate
persistence data store. Often when choosing the persistence data store the following fundamental
qualifiers are considered:
1. The length of time data must be persisted
2. The volume of data
Example:
<%@page import="org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>
<%! SessionFactory sf;

org.hibernate.Session hibSession; %>

<%
sf = new Configuration().configure().buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
String nowtime = ""+new java.util.Date();
gb.setVisitorName(username);
gb.setMsg(usermsg);
gb.setMsgDate(nowtime);
hibSession.save(gb);
tx.commit();
out.println("Thank You for your valuable feedback....");
}catch(Exception e){out.println(e);}
hibSession.close();
%>

Q. 2 With the help of a diagram explain JPA architecture.

1. Persistence: The javax.persistence.Persistence class contains static helper methods to obtain


EntityManagerFactoryinstances in a vendor-neutral fashion.

2. EntityManagerFactory: The EntityManagerFactory is created with the help of a Persistence Unit


during the application start up. It serves as a factory for spawning EntityManager objects when
required. Typically, it is created once [one EntityManagerFactory object per database] and for later
use kept alive for later use.The javax.persistence.EntityManagerFactory class is a factory for
EntityManagers.

3. EntityManager: The EntityManager object [javax.persistence.EntityManager] is lightweight and


inexpensive to create. It provides the main interface to perform actual database operations. All the
POJOs i. e. persistent objects are saved and retrieved with the help of EntityManager object.
Typically, EntityManager objects are created as needed and destroyed when not required. Each

Page 1 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

EntityManager manages a set of persistent objects and has APIs to insert new Objects and delete
existing ones. EntityManagers also act as factories for Query instances and CriteriaQuery
instances.

4. Entity: Entites are persistent objects that represent datastore records.

5. Entity Transaction: A Transaction represents a unit of work with the database. Any kind of
modifications initiated via the EntityManager object are placed within a transaction. An
EntityManager object helps creating an EntityTransaction object. Transaction Objects are typically
used for a short time and are closed by either committing or rejecting.

6. Query: Persistent objects are retrieved using a Query object. Query objects
[javax.persistence.Query] allows using SQL or Java Persistence Query Language [JPQL] queries to
retrieve the actual data from the database and create objects.

7. Criteria: Criteria API IS a non-string-based API for the dynamic construction of object-based queries
[javax.persistence.criteria]. Just like JPQL static and dynamic queries, criteria query objects are
passed to the EntityManager’screateQuery() method to create Query objects and then executed
using the methods of the Query API. A CriteriaQuery object can be thought of as a set of nodes
corresponding to the semantic constructs of the query:

 Domain objects, which correspond to the range variables and other identification variables of the
JPQL FROM clause
 WHERE clause predicates, which comprise one or more conditional expression objects
 SELECT clauses, which comprise one or more select item objects
 ORDER-BY and GROUP-BY items
 Subqueries

Page 2 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

Q. 3 What is Hibernate? Explain the need of using it.

Any project that requires database interaction have started looking at ORM tools than considering the
traditional approach i.e. JDBC. Hibernate ease the job of programmer in working with traditional
database using concrete SQL queries in Java by using java object mapped with data base and allow
programmer to interact with database just like other java class or object. The objective of Hibernate is
to free the programmer from tedious database interaction and focus on working with java objects and
features of application instead of worrying about how to work with data from database. Hibernate
does this by copying data from database table to java class and saving state of an object to database
table. Hibernate is a free, open source, high performance persistent ORM and query tool. Gavin King,
founded the Hibernate Project in 2001 at JBoss Inc. [now part of RedHat Inc.]
Hibernate provides:
 Mapping of java classes to Database table.
o e.g.: Student.java class → Student table in Oracle
 Mapping of java data type to SQL data type.
o e.g.: int → number, String → varchar, java.sql.Date → DateTime, etc.
 Flexibility in Querying and retrieving data from any database.
 Freedom to switch to any data base without changing the application logic/presentation logic.

Q. 4 What are the different components of Hibernate?

Components of Hibernate:
The main components of Hibernate are:
1. Connection Management: Hibernate solves the problems which arise when a relational database
is connected by an application written in object oriented programming language style, due to data
type differences, manipulative differences, transactional differences, structural and integrity
differences. Connection Management provides efficient connection management and removes the
overhead of database interaction from application program.
2. Transaction Management: Transaction in hibernate is managed by JTA and JDBC. It allow to fire
more than one SQL query at a time.
3. Object Relation Management: It is used to map java objects to database tables. Hibernate stores
the persistent objects in session and reads the state of an object to execute appropriate database
query.

Q. 5 Write a short note on hibernate architecture.

Hibernate is a layered architecture. The main components are Configuration, Session Factory,
Session, Transaction, Query and Criteria. Hibernate uses existing Java APIs, like JDBC for database
connectivity, Java Transaction API(JTA) for transaction and Java Naming and Directory Interface
(JNDI) for easy integration with other enterprise application

Page 3 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming
and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction offunctionality
common to relational databases, allowing almost any database with a JDBC driver to supported by
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Configuration: It represents properties/configuration of a hibernate application. It the first object created
in a hibernate application and created once at the time of application execution. This object reads the
configuration file to establish database connection and mapping. This object helps in creating session
factory. It represents a configuration or properties file required by the Hibernate. The Configuration
object provides two keys components:
1. Database Connection: This is handled through one or more configuration files supported by
Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
2. Class Mapping Setup This component creates the connection between the Java classes and
database tables.

Session Factory: It is created using configuration object at the time of application startup to
serve as a base for creating light weight sessions conveniently during client’s request. One
session factory is created for one database for multiple database multiple session factory
objects are created. Session Object: Sessions are single threaded, lightweight objects to
communicate with database represented by session class from org.hinernate package.
Persistent object are created, saved and retrieved using session object during client interaction.
It wraps the Connection class from java.sql package and serves as factory for Transaction. The
session objects should not be kept open for a long time because they are not usually thread
safe and they should be created and destroyed them as needed.
Transaction: Transaction is a single threaded object used by application to represent group of
SQL queries to form a unit of work called transaction. Transactions in Hibernate are handled by
an underlying transaction manager and transaction (from JDBC or JTA). All changes during a
session are placed within transaction. Transactions are either completed using commit or
cancelled using rollback. The org.hibernate.Transaction interface provides methods for
transaction management.
Query: It uses either conventional SQL or Hibernate Query Language (HQL) to communicate
with database. It associates the query parameters, restricts the results coming from database
and executes queries. Persistent objects are retrieved using query object.
Criteria: Criteria objects are used to create and execute object oriented criteria queries to
retrieve objects.

Page 4 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

Q. 6 Write a JSP code to add visitor’s feedback using Hibernate in FeedBack table in database.

<%@page import="org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>


<%! SessionFactory sf;
org.hibernate.Session hibSession; %>

<%
sf = new Configuration().configure().buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
String nowtime = ""+new java.util.Date();
gb.setVisitorName(username);
gb.setMsg(usermsg);
gb.setMsgDate(nowtime);
hibSession.save(gb);
tx.commit();
out.println("Thank You for your valuable feedback....");
}catch(Exception e){out.println(e);}
hibSession.close();
%>

Q. 7 Write a JSP code to add guest feedback using JPA in GuestBook table in database.

<%@page import="java.util.*,javax.persistence.*,mypack.GuestBook" %>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTransaction;
%>
<%
entityManagerFactory = Persistence.createEntityManagerFactory("JPAApplication1PU");
entityManager = entityManagerFactory.createEntityManager();
String submit = request.getParameter("btnSubmit");
try {
String guest = request.getParameter("guest");
String message = request.getParameter("message");
String messageDate = new java.util.Date().toString();
GuestBook gb = new GuestBook();
gb.setVisitorName(guest);
gb.setMessage(message);
gb.setMessageDate(messageDate);
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(gb);
entityTransaction.commit();
} catch (RuntimeException e) {
if(entityTransaction != null) entityTransaction.rollback();

Page 5 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

throw e; }
try {
guestbook = entityManager.createQuery("SELECT g from GuestBook
g").getResultList();
} catch (RuntimeException e) { }
entityManager.close();%>

Q. 8 What is Impedance Mismatch? How it can be solved?

The object oriented [domain] model use classes, whereas the relational databases use tables. This
creates a gap [The Impedance Mismatch]. Getting the data and associations from objects into relational
table structure and vice versa requires a lot of tedious programming due to the difference between the
two. This difference is called The Impedance Mismatch.

The Impedance Mismatch:


This issue arises as the design of relational data and object-oriented instances share a very different
relationship structure within their respective environments. Relational databases are structured in a
tabular manner and the object-oriented instances are structured in a hierarchical manner. This means
that in this object-oriented world, data is represented as OBJECTS [often Called DOMAIN model].
However, the storage medium is based on a RELATIONAL paradigm. Hence, there exists an inevitable
mismatch, the so-called Object/Relational Impedance Mismatch which creates a vacuum between the
Object-Oriented Model of a well-designed application [the DOMAIN model] and the relational model in a
database schema. This vacuum is surprisingly wide.

Page 6 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

Q. 9 What is the relationship between JPA, ORM, Database and the application?

JPA is made up of a few classes and interfaces. The application communicates with the configured IPA
provider [in this case EclipseLink] to access the underlying data. Typically, applications invoke the
appropriate methods of the Java Persistence API. These methods are passed the persistence objects
and instructed to operate upon them. The information about the mapping [metadata] between the
instance variables of classes and the columns of the tables in the database is available either in XML
and/ or POJOs with the help of Annotations. POJOs are Java classes that represent the tables in the
database. Data Access Object [DAO] is the design pattern that can be used [if required] to deal with
database operations.’
EclipseLink uses the database [using JDBC API internally] and refers to the metadata to provide
persistence services [and Persistent Objects] to the application. The application talks to EclipseLink via
the JPA to perform the SELECT, INSERT, UPDATE and DELETE operations on the database tables.
The ORM tool automatically creates the required SQL queries and fires them using the JDBC APIs.

Q. 10 Write short note on Functions in JPQL and Downcasting in JPQL.

Functions in JPQL:
JPA supports a set of database functions which you can use to perform small operations and
transformations within a query. This is often easier and faster than doing it in the Java code. SQL
supports a lot more database functions than JPQL, Specific database vendors also provide their own set
of functions. Users and libraries can also define their own database functions. JPA 2.0 JPQL provided
no mechanism to call database specific functions.
JPA 21 introduced function() to call database functions which are not directly supported by the standard.
The syntax is very easy. You need to provide the name of the function as the first parameter and then all
parameters of the custom function. In following example, the name of the function is "calculate" and I
provide the numbers 1 and 2 as parameters.
Example:
Author a = em.createQuery("SELECT a FROM Author a WHERE a.id = function('calculate', 1, 2)",
Author.class).getSingleResult();

Downcasting in JPQL:
JPQL will be extended to cast in the FROM and WHERE clause. The format of this will use the keyword
"TREAT" and be part of the join clause. The operator TREAT can be used to cast an entity to its
subclass value, i.e. downcast related entities with inheritance. This is typically used in JOIN queries

Page 7 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

where we want to impose a restriction in WHERE clause involving a subclass field. The following is an
example:

Example:
select e from Employee e join TREAT(e.projects AS LargeProject) lp where lp.attribute = value

Q. 11 How hibernate works? / Explain the modus operandi behind hibernate application.

• All configuration files hibernate.cfg.xml are created to describe about the java classes and there
mapping with database tables.
• At the time of application startup these files are compiled to provide hibernate framework with
necessary information.
• This dynamically builds java class objects by mapping them to appropriate database table.
• A session factory object is created from compiled collections of mapping documents.
• Session Factory spawns a lightweight session to provide interface between java objects and
applications.

• Database communication is performed by this session using hibernate API used to map the changes
from java object to database table and vice versa.

Q. 12 Explain the structure of hibernate.cfg.xml.

Hibernate requires to know in advance that, where to find the mapping information that defines how
your Java classes relate to the database tables. Hibernate also requires a set of configuration settings
related to database and other related parameters. All such information is usually supplied as a standard
Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.

We will consider XMI. formatted file hibernate.cfg.xml to specify required Hibernate properties in
following example. Most of the properties take their default values and it is not required to specify them
in the property file unless it is really required. This file is kept in the root directory of your application's
classpath.

Page 8 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
TRAINING -> CERTIFICATION -> PLACEMENT BSC IT : SEM – V Enterprise Java : UNIT 5

We will be required to configure for a databases in a standalone situation following properties:

 hibernate.dialect: This property makes Hibernate generate the appropriate SQL for the chosen
database.
 hibernate.connection.driver class: The JDBC driver class.

 hibernate.connection.url: The JDBC URL to the database instance


hibernate.connection.username: The database username.

 hibernate.connection.password: The database password.

 hibernate.connection.pool size: Limits the number of connections waiting in the Hibernate


database connection pool.

 hibernate.connection.autocommit: Allows autocommit mode to be used for the JDBC connection

If you are using a database along with an application server and JNDI, then you
would have to configure the following properties:

 hibernate.connection.datasource: The JNDI name defined in the application server context,


which you are using for the application.
 hibernate.jndi.class: The InitialContext class for JNDL
 hibernate.jndi.<JNDIpropertyname>: Passes any JNDI property you like to the JNDI
InitialContext.
 hibernate.jndi.url: Provides the URL for JNDI.
 hibernate.connection.username: The database username.
 hibernate.connection.password: The database password.

The following sample file gives some insight of hibernate,cfg.xml file where MySQL is used as
database server for the application.

<?xml version="1.0" encoding="utf-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>

Page 9 of 9
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622

You might also like