Enterprise Java Sem: V
Enterprise Java Sem: V
com
Acuity Educare
ENTERPRISE JAVA
SEM : V
SEM V: UNIT 1
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.
Performance: The ability of an application to respond to a client request in the minimum time.
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
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
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
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.
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
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.
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
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
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
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.
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.
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.
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
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
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
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
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>");
}
}
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.
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
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.
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.
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>
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.
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
Q. 21 Enlist and Explain the steps of database connectivity using JDBC API.
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
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)
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
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.
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
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);
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.
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;
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
ac.complete();
t.printStackTrace();
}
}
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.
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.
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.
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
ac.complete();
t.printStackTrace();
}
}
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);
}
}
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
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.
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().
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
Q.1 What are the benefits of using JSP?/ Explain the reason why use JSP?
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
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.
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:
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.
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
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
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.
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.
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
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
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
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)
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>
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:
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>"/>
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.
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.
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
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.
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
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.
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
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.
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.
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
Defining an Interceptor:
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.
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
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.
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
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. 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
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
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.
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).
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
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.
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.
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
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;
<%
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();
%>
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.
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
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.
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.
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.
<%
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 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();%>
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.
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.
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.
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
hibernate.dialect: This property makes Hibernate generate the appropriate SQL for the chosen
database.
hibernate.connection.driver class: The JDBC driver class.
If you are using a database along with an application server and JNDI, then you
would have to configure the following properties:
The following sample file gives some insight of hibernate,cfg.xml file where MySQL is used as
database server for the application.
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