View
223
Download
0
Category
Preview:
Citation preview
7/27/2019 JavaEE Related Technologies
1/15
Java EE Related Technologies
1
Chapter 2: Java EE Related Technologies
Syllabus:
1. Java Database Connectivity2. Servlets3. JavaServer Pages4. Java Server Faces5. JavaMail6. Enterprise JavaBeans7. Hibernate8. Seam9. Java EE Connector Architecture10.Web Services11.Strut12.Spring13.JAAS14.AJAX
Check regularly it will be updated till final exam day
Java Database Connectivity (JDBC)
Why we need JDBC?
Many enterprise applications that are created using Java EE technology, need to interact withdatabases for storing application specific information. For example, Search engines use databasefor storing information about the web pages; Job portals use database for storing informationabout the candidates and employers, accessing the site for searching and advertising jobs on theInternet. However, interacting with database requires database connectivity. This can be achievedby using the ODBC driver, which is used with Java Database Connectivity (JDBC) to interact withdatabases such as Oracle, Ms Access, and SQL Server. JDBC is an API, which is used in Java
programming for interacting with database.
JDBC is used for providing database connectivity to enterprise applications. Java uses the JDBCAPI, which helps connect to a database using Java code. JDBC works with different database
drivers for connecting to different database.
Introduction to JDBC
Sun has introduced a common specification API, called JDBC. In general, the term JDBC is referredas Java Database Connectivity. JDBC is a specification from Sun Microsystems that provides a
standard abstraction (API/Protocol) for Java applications to communicate with different databases.It is used to write programs that need to access databases. JDBC, along with the database driver,is capable of accessing databases, spreadsheets, and flat files.
We can say that JDBC is a platform-independent interface between a relational database and theJava programming language. Therefore, we can say that JDBC is a standard API to accessenterprise data in a relational database. The JDBC API allows Jaya programs to execute SQLstatements and retrieve the results according to the statements. JDBC also provides methods to
return error message while accessing a database. JDBC provides classes and interfaces that allow
a Java application to send requests made by users to the specified DBMS. The users may notspecify any specific DBMS for the requested data; rather they can use the drivers to target aspecific database for the user requests. JDBC provides the following characteristics, which makes itmore efficient in comparison to ODBC:
JDBC is simple and easy to use.JDBC supports a wide level of portability.JDBC provides Java interfaces compatible with lava application and is also responsible forrepresenting the driver services.JDBC can be used as a higher level API for the application programmers. The JDBC APIspecification is used as an interface for the application and the DBMS.
JDBC specification provides JDBC API for Java applications. The JDBC call to a Javaapplication is made by the SQL statements. These statements are responsible for the entire
communication of the application with the database. The user can request any type of SQLqueries to a database. The JDBC drivers are responsible for querying the database for the
7/27/2019 JavaEE Related Technologies
2/15
Java EE Related Technologies
2
SQL queries and retrieving the results.
Components of JDBC
JDBC has four main components through which it communicates with a database. Thesecomponents are:
1. The JDBC API The JDBC API provides various methods and interfaces for easy andeffective communication with the database. It provides a standard for connecting a
database to a client application. The application specific user processes the SQL commands
according to his need and retrieves the result in the ResultSet object. The JDBC API
provides two main packages, java.sql and javax.sql, for interacting with databases. Both
the packages contain the Java SE and Java EE platforms, which conform to the "write once
run anywhere (WORA)" capabilities of Java.2. The JDBC DriverManagerDriverManager is one of the most important components of
JDBC. DriverManager loads database-specific drivers in an application to the database. It is
also used to select the most appropriate database-specific driver from the previously loadeddrivers when a new connection to the database is established. In addition, it is used tomake database-specific calls to the database to process the user requests.
3. The JDBC Test SuiteDue to existence of multiple JDBC drivers in the market. JDBCcomes with a Test Suite that is used for evaluating the JDBC drivers for its compatibilitywith Java EE. The JDBC test suite is used to test the operations being performed by JDBCdrivers.
4. The JDBC-ODBC BridgeThe JDBC-ODBC Bridge is used to connect database drivers tothe database. This driver translates JDBC method calls to ODBC function calls. The bridge isused to implement JDBC for any database for which an ODBC driver is available. The bridge
for an application can be availed by importing the sun.jdbc.odbc package, which contains
a native library for accessing the ODBC features.
JDBC Specification
JDBC has undergone major changes with the emergence of JDBC 4.0. Let's discuss thespecifications available in different versions of JDBC:
JDBC 1.0 Provides basic functionality of JDBC.JDBC 2.0 Provides JDBC API in two parts: the JDBC 2.1 Core API and the JDBC 2.0Optional Package API.
JDBC 3.0 Provides classes and interfaces in two Java packages: java.sql and
javax.sql.
JDBC 3.0 is combination of JDBC 2.1 core API and the JDBC 2.0 Optional Package API. TheJDBC 3.0 specification provides performance optimization features and improves thefeatures of connection pooling and statement pooling, and also provides a migration path toSun Microsystems connector architecture.
JDBC 4.0- Provides following advance features:o Auto loading of the Driver interfaceo Connection managemento ROWID data type supporto Annotation in SQL querieso National Character Set Conversion Supporto Enhancement to exception handlingo Enhanced support for large objects
The PBC 4.0 is the new and advance specification used with Java EE 5.
JDBC Architecture
A JDBC driver is required to process the SQL requests and generate the results. JDBC API providesclasses and interfaces to handle database specific calls from users. Some of the important classesand interfaces are:
Connection
DatabaseMetaDataPreparedStatement
7/27/2019 JavaEE Related Technologies
3/15
Java EE Related Technologies
3
StatementDriver
CallableStatementResultSetDriverManagerResultSetMetaData
SqlDataBlobClob
The DriverManager in the JDBC API plays an important role in the JDBC architecture. It uses some
database specific drivers to effectively connect enterprise applications to databases. Figure 2-1demonstrates the simple JDBC architecture.
Figure 2-1: Architecture of JDBC
As shown in Figure 2-1, the Java application that wants to communicate with a database has to beprogrammed using JDBC API. The JDBC driver (third party vendor implementation) supporting
datasource such as Oracle, and SQL, has to be plugged in to the drive, which can be donedynamically at runtime. This ensures that the Java application is vendor independent. Therefore, ifwe want to communicate with any data source through JDBC, we need a JDBC driver, which
intelligently communicates with the respective data source. Currently, we have 720 plus JDBCdrivers available in the market, which are designed to communicate with different data source.Some of these drivers are Pure Java drivers and are portable for all the environments whereasothers are Partly Java drivers and require some libraries to communicate with the database. We
need to understand the architectures of all the four types of drivers to decide which driver to useto communicate with our required data store. Let's now learn about each of these drivers in detail.
JDBC Drivers
The different types of drivers available in JDBC are listed in below:
JDBC Drive Types Description
Type-1 Driver This type of driver is Bridge Driver (JDBC-ODBCbridge)
Type-2 Driver This driver is a Partly Java and Partly Nativecode driver
Type-3 Driver This is a Pure Java driver that uses amiddleware driver to connect to a database
Type-4 Driver This is a Pure Java driver and is directlyconnected to a database
7/27/2019 JavaEE Related Technologies
4/15
Java EE Related Technologies
4
Describing Type-1 Driver
The Type-1 driver acts as a bridge between JDBC and other database connectivity mechanisms,such as ODBC. An example of this type of driver is the Sun JDBC-ODBC bridge driverimplementation. The JDBC-ODBC Bridge provides the access to the database by using the ODBCdrivers. This driver helps the Java programmers to use JDBC and programs Java applications to
communicate with existing data stores. This driver is included in the Java2 SDK within the sun.
jdbc.odbc package. This driver converts JDBC calls into ODBC calls and redirects the request to
the ODBC driver. The architecture of the Type-1 driver is shown in Figure 2-2:
Figure 2-2: The architecture of the Type-1 driver
Figure 2-2 shows the architecture of the system that uses JDBC-ODBC bridge driver tocommunicate with the respective database. As shown in the figure Java Application is programmedto JDBC API and will make a request to JDBC-ODBC bridge driver i.e. JDBC call, where JDBC-ODBCbridge driver is responsible to resolve the JDBC call and make an equivalent ODBC calls to the
ODBC driver. To do this JDBC-ODBC bridge driver uses ODBC API. Later ODBC driver comes intoaction and completes the request, and sends response to the JDBC-ODBC bridge driver. Now,JDBC-ODBC bridge driver converts the response and presents it to the requesting Java Applicationin JDBC standards. This type of driver is generally used in the development and testing phases ofJava applications.
Advantages of Type-1 Driver
Single Driver implementation can be used to interact with different data stores.
This driver allows us to communicate with all the databases supported by the ODBC driver.This is a vendor independent driver.
Disadvantages of Type-1 Driver
Due to a large number of translations, the execution speed is decreased.This driver depends on the ODBC driver, and therefore, Java applications also become
indirectly dependent on ODBC drivers.ODBC binary code (or ODBC client library) must be installed on every client.This driver uses JNI to make ODBC calls.
Because of the preceding listed disadvantages, this driver is not recommended to be used inproduction environment. In case a database does not have any other JDBC driverimplementations, then only we should use this driver in the production environment.
Describing Type-2 Driver (Java to Native API)
7/27/2019 JavaEE Related Technologies
5/15
Java EE Related Technologies
5
Type-2 driver converts JDBC call into DB vendor specific native call in a client machine. In otherwords, this type of driver makes JNI calls on database specific native client API. These database
specific native client API are usually written in C, C++. The Type-2 driver follows a 2-tierarchitecture model, as shown in Figure 2-3:
Figure 2-3: The architecture of the Type-2 driver
As shown in Figure 2-3, the Java application that wants to communicate with the database isprogrammed using JDBC API. These JDBC calls (programs written by using JDBC API) areconverted into database specific native calls in the client machine and the request is thendispatched to the database specific native libraries. These native libraries present in the client areintelligent to send the request to the database server by using native protocol.
This type of driver is implemented specific to a database and is usually delivered by a DBMSvendor. However, it is not mandatory that Type-2 drivers have to be implemented by DBMS
vendors only. An example of Type-2 driver is the Weblogic driver implemented by BEA Weblogic.Type-2 drivers are suitable to use with server-side applications. It is not recommended to useType-2 drivers with client-side applications, since the database specific native libraries for theclient platform should be installed on the client machines.
Advantages of Type-2 Driver
This driver helps in accessing the data faster as compared to other type of driversWe can use the additional features provided by the specific database vendor, which are
even supported by the JDBC specification.
Disadvantages of Type-2 Driver
Native libraries must be installed on client machines since the conversion from JDBC calls to
database specific native calls is done on the client machine.Database specific native functions are executed on the client JMV process and any bug in
this driver can crash the JVM.It may increase the cost of the application if the application needs to run on differentplatforms (since we may require buying the native libraries for all of the platforms).
Examples of Type-2 Driver
OCI (Oracle Call Interface) DriverOracle Corporation has implemented this driver tocommunicate with the Oracle database server. This driver converts JDBC calls into OCI(Oracle native libraries) calls.Weblogic OCI Driver for Oracle This driver is also similar to the oracle OCI driver, but
the Weblogic OCI JDBC driver makes JNI calls to weblogic library functions.
Type-2 Driver for Sybase This driver converts JDBC calls into Sybase dblib or ctlib calls,which are native libraries to connect to Sybase.
7/27/2019 JavaEE Related Technologies
6/15
Java EE Related Technologies
6
Describing the Type-3 Driver (Java to Network Protocol/All Java Driver)
The Type-3 driver translates JDBC calls into database server independent and middleware serverspecific net protocol calls (network calls), which are then translated into database server specificcalls by the middleware server. Type-3 drivers follow 3-tier architecture model, as shown in Figure2-4:
Figure 2-4: The architecture of the Type-3 driver
As shown in Figure 2-4, JDBC Type-3 driver listens for JDBC calls from the Java application andtranslates them into middleware server specific calls. Then, the driver communicates with the
middleware server over a socket. The middleware server converts these calls into database specificcalls. This type of drivers are named as net-protocol fully Java technology-enabled driver, orsimply net-protocol driver.
The middleware server can be added with some additional functionalities, such as pool
management, to improve the performance and availability of connection, which can make thisarchitecture more useful in enterprise applications. Type-3 driver is recommended to be used withapplets since this type of driver is auto downloadable.
Advantages of Type-3 Drivers
Type-3 drivers are pure Java drivers and are auto downloadable.No native libraries are required on the client machine.A single driver provides accessibility to multiple databases, implying that this driver is
database independent.Database details, such as username, password, and database server location, are notrequired to be given to the client; instead, they are configured in the middleware server.We can switch over from one database to other without changing the client-side driver
classes, by just changing the configurations of the middleware server.
Disadvantages of Type-3 Driver
Compared to Type-2 drivers, Type-3 drivers are slow due to the increased number ofnetwork calls.Type-3 drivers are costlier compared to the other drivers.
Examples of Type-3 Drivers
IDS Driver This driver listens for JDBC calls and converts them into IDS Server specificunderstandable network calls. A Type-3 driver communicates over a socket to IDS Server,which acts as a middleware server (as described in the architecture).
Weblogic EMI Driver This driver listens for JDBC calls and sends the request from the
client to the middleware server by using the RMI protocol. The middleware server uses asuitable JDBC driver to communicate with a database.
7/27/2019 JavaEE Related Technologies
7/15
Java EE Related Technologies
7
Describing the Type-4 Driver (Java to Database protocol)
The Type-4 driver is a pure Java driver, which implements the database protocol to interactdirectly with a database. This type of drivers does not require any native database libraries toretrieve the records from the database. This type of drivers translates JDBC calls into Databasespecific network calls. Type-4 drivers follow the 2-tier architecture model, as shown in Figure 2-5:
Figure 2-5: The architecture of the Type-4 driver
As shown in Figure 2-5, the Type-4 driver prepares a DBMS specific network message and then
communicates with database server over a socket. This type of driver is lightweight and isgenerally known as thin driver. The Type-4 driver uses data base specific proprietary protocols forcommunication. Generally, this type of drivers are implemented by DBMS vendors, since theprotocol used here are proprietary.
You can use Type-4 drivers when you want an auto downloadable option for the client-sideapplications. It is also recommended to be used with server-side applications.
Advantages of Type-4 Driver
This type of drivers are pure Java drivers and hence auto downloadable.
No native libraries are required to be installed in the client machine.Secure to use since it uses database server specific protocol.This type of driver does not require a middleware server.
Disadvantage of Type-4 Driver
The main disadvantage of Type-4 Driver is that it uses database specific proprietary protocol and isDBMS vendor dependent.
Examples of Type-4 Driver
Thin Driver for Oracle from Oracle Corporation
Weblogic, Msssqlserver4 for MS SQL Server from BEA Systems
Servlets
Java Servlets technology provides a simple, vendor independent mechanism for extending the
functionality of a Web server. This technology provides high level, component-based, platform-independent, and senwr-independent standards to develop Web applications in Java. The Servlettechnology is similar to other scripting languages, such as Common Gateway Interface (CGI)scripts, JavaScript (on the client side), and PHP. However, Servlets are more acceptable since they
overcome the limitations of CGI, such as low performance and scalability.
What is a Servlet?
A Servlet is a simple Java class, which is dynamically loaded on a Web server and thus enhancesthe functionality of the Web server. A Servlet is secure and portable as it runs on Java Virtual
7/27/2019 JavaEE Related Technologies
8/15
Java EE Related Technologies
8
Machine (JVM) embedded with Web server and cannot operate outside the domain of Web server.In other words, Servlets are objects that generate dynamic content after processing the requests
originated from a Web browser. Servlets are Java components that are used to create dynamicWeb applications. They can run on any Java-enabled platform and are usually designed to processHTTP requests, such as GET, and POST.
Servlet API includes two packages:
1. javax.servlet and2. javax.servlet.http
For writing the Servlets, the javax.servlet and javax.servlet.http packages provide interfaces
and classes.
Servlet Life Cycle
Servlets follow the life-cycle, which governs the multithreaded environment that Servlets run inand provides an insight to some of the mechanisms available to a developer for sharing server-sideresources.
The primary reason why Servlets and JSP outperform traditional CGI is the Servlet life-cycle. TheServlets follow a three-phase life namely: (ISD)
1. Initialization,2. Service, and3. Destruction.
This three-phase lifecycle is opposed to the single-phase life-cycle. Among the three phases, theServlet typically performs only once with initialization and destruction while the service is
performed many times.
Initialization Phase
The first phase of the Servlet life-cycle is initialization. It represents the creation and initializationof resources the Servlet may need in response to service requests. All Servlets must implement
the javax.servlet.Servlet interface. This interface defines the init() method to match the
initialization phase of a Servlet life-cycle. As soon as a container loads a Servlet, it invokes the
init() method prior to servicing any requests.
Service Phase
The service phase is the second phase of a Servlet life-cycle. This phase of Servlet life-cyclerepresents all interactions along with requests until the Servlet is destroyed. The Servlet interface
matches the service phase of the Servlet life-cycle to the service() method. The service()
method of a Servlet is invoked once as per the request. Then, it is solely responsible for generating
the response to that request. The Servlet specification defines the service() method to take two
parameters, which are:
1. javax.serviet.ServletRequest and2. javax.servlet.ServletResponse object.
These two objects represent a client's request for the dynamic resource and the Servlet's response
to the client. By default, a Servlet is multithreaded which means that, typically only one instanceof a Servlet is loaded by a Web container at any given time. Initialization of this phase is done only
once, and after that, each request is handled concurrently by threads executing the Servlet's
service() method.
Destruction Phase
The destruction phase is the third and final phase of the Servlet life-cycle. The destruction phase ofthe Servlet life-cycle represents the removal of the Servlet from the Container. In this case, the
Servlet interface defines the destroy() method to correspond to the destruction life-cycle phase.
When time comes that a Servlet is about to be removed, a container calls the destroy() method.
By doing this, it is allows the Servlet to gracefully terminate and tidy up any resources it mighthave created. A Servlet can efficiently manage application resources only when it properly uses all
the three phases of its life-cycle. During initialization, a Servlet loads everything it needs to use forservicing requests. The resources are then readily used during the service phase and then can be
7/27/2019 JavaEE Related Technologies
9/15
Java EE Related Technologies
9
cleaned up at the final stage that is in the destruction phase.
We have discussed about these three events or phases which form the Servlet life-cycle. However,in practice, there are many more methods that a Web developer needs to worry about. Content onthe Web is primarily accessed via the Hyper Text Transfer Protocol (HTTP). A basic Servlet knowsnothing about HTTP, but at the same time, there's a special implementation of Servlet,
javax.serviet.http.HttpSerylet . It is designed especially for it.
At the time of creation of the Servlet for the first time, its init() method is invoked, and
therefore, init() can be found where you put the one-time setup code. After this, each user
request results to a thread. This calls the service() method of the previously created instance.
Although, the Servlet in question can implement a special interface (SingleTreadModel) that notonly stipulates that only a single thread be permitted to run at a time but also multiple concurrent
requests, normally result in multiple threads calling service simultaneously. The service() method
then calls doGet(), doPost(), or another doXxx() method. However it depends upon the type of
HTTP request it receives. Finally, when server decides to unload a Servlet, it first calls the Servlets
destroy() method.
The init() Method
As mentioned earlier, the init() method is called when the Servlet is created for the first time. Itis not called again for other user request. Therefore, it is used for one-time initializations only, justas with the init() method of applets. This Servlet is normally created when a user invokes a URL
for the first time corresponding to the Servlet, but the Servlet is loaded on the server when the
container maps the user request to the Servlet, The init() method definition looks like this:public void init() throws ServletException
{
// Initialization code...
}
Reading the server-specific initialization parameters is one of the most common tasks that init()
method performs. For example, the Servlet might need to know different aspects such as databasesettings, password files, server-specific performance parameters, hit count files, or serialized
cookie data from previous requests. Initialization parameters let the Servlet to deploy (for examplethe server administrator) and also customize the Servlet.
When you require to read initialization parameters, firstly, you have to obtain a ServletConfig
object by means of getServletConfig(), and then you have to call getInitParameter on the
result.
The init() method uses getServletConfig() to obtain a reference to the ServletConfig object;
and the ServletConfig has a getInitParameter() method with which you can look up
initialization parameters associated with the Servlet. Just as with the getParameter() method
used in the init() method of applets, both the input (that is the name of the parameter) and the
output (that is the parameter value) are nothing but Strings. By calling the getInitParameter()
method ofServletConfig, you can read initialization parameters but, the question is, how do you
set them? That is the job of the web.xml file, which is called as the Deployment Descriptor.
The service() Method
As per the service() method, each time when the server receives a request for a Servlet, the
server spawns a new thread and calls for service(). The service() method checks the HTTP
request type (GET, POST, PUT, DELETE) and calls doGet(), doPost(), doPut(), doDelete() as
appropriate. Here, a GET request results from a normal request for a URL or from an HTML formthat has no METHOD specified. The POST request results from an HTML form that specifically listsPOST as the METHOD. For example:
Other HTTP requests are generated only by the custom clients.Now, if you have a Servlet that needs to handle both POST and GET requests identically, you may
be tempted to override service() directly rather than implementing both doGet() and doPost().However, remember, this is not a good idea. Instead of it, you just have to stick to doPost() call
7/27/2019 JavaEE Related Technologies
10/15
Java EE Related Technologies
10
doGet() (or vice versa), as shown here:@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException)
{
// Servlet code
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
The doGet(), doPost(), and doXxx() methods
During the entire request and response process, most of the time, you only care about GET or
POST requests. Therefore, you override doGet() and/or doPost(). However, if you want to, you
can also override doDelete() for DELETE requests, doPut() for PUT, doOptions() for OPTIONS,
and doTrace() for TRACE.
The destroy() Method
In the destroy() method, the server may decide to remove a previously loaded Servlet instance,
perhaps because it is explicitly asked to do so by the server administrator. It also may do itperhaps because the Servlet is sitting idle for a long time. Before it removes a previously loaded
Servlet instance, it calls the Servlet's destroy() method. This method gives your Servlet a chance
to close database connections, halt background threads, write cookie lists or hit counts to disk, and
perform other such cleanup activities.
Note: Be aware, however, that it is possible for the Web server to crash. Therefore, do not counton destroy as the only mechanism for saving state to disk. Activities like hit counting or
accumulating lists of cookie values that indicate special access should also proactively write theirstate to disk periodically.
Hibernate
Hibernate provides a framework for mapping an object-oriented domain model to a relationaldatabase. The primary feature of Hibernate is to map JavaBean classes to database tables.Hibernate helps in querying and retrieving data from database tables. In addition, Hibernate
generates the SQL calls and so the developers do not need to provide Java code for handlingresultsets. Hibernate ensures that a Web application is portable with all SQL supported databases.
Hibernate also provides persistence feature for Plain Old Java Objects (POJOs). Hibernate can beused both standalone Java applications and in Java EE applications using Servlets or EJB sessionbeans.
Introduction to Hibernate
Hibernate is a lightweight Object/Relational mapping (ORM), which is a technique for mapping anobject model to a relational model. Hibernate handles mapping from Java classes to database
tables, and provides API for querying and retrieving data from database. This helps to writesophisticated query by using Hibernate Query Language (HQL) that reduces the time spent inhandling data by using SQL and JDBC. It relieves the developer from 95 percent of a common datapersistence related programming tasks, compared to manual coding with SQL and the JDBC API.
Hibernate uses a transparent programming model for mapping Java objects to the relational
databases. You only need to write a simple POJO (Plain Old Java Object) and create an XMLmapping file that describes relationship between the database and the class attributes by using
7/27/2019 JavaEE Related Technologies
11/15
Java EE Related Technologies
11
object/relational mapping tool and call a few Hibernate APIs to load/store the persistent objects.Hibernate fills the gap between Object-oriented systems and relational databases. It allows
transparent persistence that enables the applications to use any RDBMS software. Hibernate worksefficiently with applications that use Swings, Servlets, and EJB Session beans. It does not requiredevelopers to implement interfaces or extend classes to be persistent. It has extensive support ofJava collections API (Map, Set, List, SortedMap, SortedSet, and Collection).
Why Hibernate?
Hibernate is a technology that provides solution for object relational mapping and persistencemanagement. The reasons for using Hibernate are as follows:
Supports natural Object-oriented Programming model, such as inheritance, polymorphism,
composition, abstraction, and the Java collections frameworkProvides developers with persistence feature and a code generation library, CGLIB toextend Java classes and implement Java interfaces at runtime environment. If any changes
are made to objects associated with a transaction, they are automatically detected andpropagated to the database. This saves the time spent in extra coding for bytecodeprocessing.Provides Object-oriented query language called Hibernate Query language (HQL), which is
similar to SQL. HQL is an ORM query language defined by EJB 3.0. It helps in writing multi-criteria search and dynamic queries much easier. Queries may be polymorphic and can useany abstract superclass or interfaceProvides Object/Relational mapping for bridging the gap between Object-oriented systems
and relational database.Enables the developer to build Hibernate Web application very efficiently in MyEclipse byusing Hibernate eclipse plug-ins that provide mapping editor, interactive query prototyping,schema reverse engineering tool.Reduces the development timings as it supports Object-oriented programming, such asinheritance, polymorphism, composition, and also support Java Collection framework.Provides Id generator classes to generate surrogate keys also called unique keys/identifiers.
Some of the classes are:
o Nativeo Identityo Sequenceo Incremento HI/L0 algorithmo UUID algorithm
Provides hibernate Multi level Cache Architecture for thread safety and continuous dataaccess.Provides features, such as Lazy initialization and Eager or Batch fetching for improving theperformance
Provides integration with Java EE.Can operate in managed or non-managed environments. It can run outside an application
server container, within standalone applications. This facilitates the following:o SessionFactory can be easily bound to JINDIo Stateful Session bean or in a servlet HttpSession with load balancing can include
Sessiono JDBC connections may be provided by application data sourceo Hibernate Transaction system integrates with Java EE applications via JTA (Java
Transaction API)o Automatic binding of Hibernate Session to the global JTA transaction scope
The Hibernate architecture
The Hibernate architecture consists of two technologies Hibernate and Java EE. Hibernate makesuse of the existing Java APIs, including JDBC (Java Database Connectivity), Java Transaction API
(JTA), Java Naming and Directory Interface (JNDI). JDBC loads database driver and establish aconnection for accessing relational database. It uses all types of database driver that aresupported by Hibernate. JNDI and JTA allow Hibernate to be integrated with application servers.
7/27/2019 JavaEE Related Technologies
12/15
Java EE Related Technologies
12
Figure shows the architecture of Hibernate.
Figure: The Hibernate architecture
Hibernate Query Language
Hibernate Query Language (HQL) is an easy-to-learn and powerful query language designed as an
Object-oriented extension to SQL that bridges the gap between the Object-oriented systems andrelational database. The syntax of HQL is very similar to SQL. It has a rich and powerful Object-oriented query language available with the Hibernate object/relational mapping (ORM). The termORM refers to the technique of mapping objects and databases. The data from Object-orientedsystems are mapped to relational databases with a SQL-based Schema
HQL queries are case-insensitive, but the names of Java classes and properties are case-sensitive.It is used to execute queries against database. Hibernate automatically generates the SQL queryand executes it, if HQL queries are used in the application. HQL uses classes and properties insteadof tables and columns. HQL supports polymorphism and associations and requires less coding than
SQL. It also supports many other SQL statements and aggregate functions, such as sum(), max()
and clauses, such as group by and order by. Learning HQL is much easier as compared to SQL.
The other options that can be used while using Hibernate are Query By Criteria (QBC) and QueryBy Example (QBE) using Criteria API and the Native SQL queries. It even supportsprojection/aggregation and subselects.
HQL is used for retrieving objects from database through O/R mapping. Thus, HQL provides thefollowing:
Applying restrictions to properties of objectsOrdering the results returned by a queryPagination of results
Aggregation using group by, having clausesJoinsUser-defined functionsSubqueries
7/27/2019 JavaEE Related Technologies
13/15
Java EE Related Technologies
13
Struts
Struts 2 is a Web application framework based on Model-View-Controller (MVC), and is used tobuild high-performance and business-oriented Web applications. Before the introduction of Struts,there was no standard component framework to develop Java EE Web applications. Themechanism to reuse the model part of the MVC architecture was only available in the form of
JavaBeans. The Struts framework was introduced to support the development of a Web application
with its set of APIs. These APIs provide a specific architecture and a mechanism to reuse themodel, view, and, controller parts of a Web application.
Getting Started with Struts 2
Struts 2 is an open source framework for creating Java Web applications; or in other words, it isreleased to the public domain free of charge. The Struts 2 framework is designed to helpdevelopers in creating Web applications based on MVC architecture. Since Struts 2 is based on theMVC architecture; it separates the business logic code, page design code, and navigational code
into three different components called model, view, and controller. This separation of concerns intocomponents helps developers to easily maintain large Web applications.
The Struts 2 framework includes a library of mark-up tags, which are used to create dynamic data.
These mark-up tags interact with the validation mechanism of Struts 2 to ensure that the output is
correct.The tag library can be used with JSP, Velocity, FreeMarker, JavaServer Pages Standard Tag Library
(JSTI), and AJAX technology.
Struts 1 was the first version of the Struts framework. With the changing technology, the need fornew enhancements and changes was felt in the original design of Struts 1. These changes include
development of new and lightweight MVC-based frameworks such as Spring, Stripes, Tapestry, andso on, to enable rapid development of Web applications. Therefore, it became necessary to modifythe Struts framework. Two new frameworks, Shale and Struts Ti were introduced in response to
the growing need for rapid development of Web applications. Then in March 2002, the WebWorkframework was released. WebWork includes new ideas, concepts and functionality with the originalStruts code. In December 2005, WebWorks and the Struts Ti merged to develop Struts 2.
Struts 2 has features similar to Struts 1, but the Struts 2 framework has some architectural
differences as compared to Struts 1. In general, the Struts 2 framework implements the MVC 2architecture by centralizing the control using a front controller strategy similar to Struts I.However, the basic code of components and their configuration is quite different in Struts 2.
7/27/2019 JavaEE Related Technologies
14/15
Java EE Related Technologies
14
Figure: MVC Pattern in Struts 2
MVC 2 Design pattern for Struts 2
The Struts 2 framework follows the MVC 2 design pattern, where model, view, and controller
components are represented by Action, Result and FilterDispatcher classes, respectively.
Figure shows the implementation of the MVC pattern by Struts 2 components.
The steps for the work flow in Struts 2 are as follows:The user sends a request through a user interface provided by the view, which further
passes this request to the controller represented by FilterDispatcher class in Struts 2.
The controller servlet filter receives the input request coming from the user through theinterface provided by the view, instantiates an object of the suitable action class, andexecutes different methods over this object.
If the state of model is changed, all the associated views are notified about the changes.Then the controller selects the new view to be displayed according to the result codereturned by the action class.
The view presents the user interface. The view queries about the state of the model toshow the current data, which is retrieved from the action class.
Struts 2 Architecture
Since Struts 2 contains various framework components such as built-in classes, servlets, andStruts tags. All framework components work together in a standard manner. The architecture of
Struts 2-based application defines the relationship and interaction between these frameworkcomponents.
Components of a Struts 2-Based Application
The architecture of a Struts 2-based application has been shown in Figure. The business logic
component allows the model layer to store only the state of a Web application. The componentscreated in the new group are known as action classes.
Controller
The controller receives the requests from users and decides where to send the request. The main
goal of the controller is to map the request URI to an Action class using the mappings provided inthe Struts-config.xml There is a single Controller Servlet and all requests go through this
Servlet which is provided by the framework itself.
The controller component available in Struts 2 framework is the ActionServlet class that
represents the controller in the MVC design pattern. ActionServlet class implements both the
front controller and singleton pattern. The front controller pattern allows for a centralized accesspoint for presentation-tier request handling, the singleton pattern provides a single instance of anobject.
The ActionServlet instance selects and invokes an Action class to perform the requested
business logic. The action classes do not produce the next page of the user directly; rather it is the
duty of the RequestDispatcher class to forward the control to an appropriate JSP page. Generally,
the Servlet engine uses RequestDispatcher.forward() method of the Servlet API to perform thistask.
The Struts-config.xml File
The Struts-config.xml file contains the transformation and configuration information for the
Struts application. It provides information regarding various Struts resources, such'as action,classes, and interceptors.
Action Classes
Action classes implement the business logic, or, in other words, they behave as wrappers aroundthe business logic and interact with the model of the application. They are basically responsible forexecuting the business service according to user requests.
Model
7/27/2019 JavaEE Related Technologies
15/15
Java EE Related Technologies
15
Model represents the data objects with the help of JavaBeans. In Struts 2, the model is
represented by org.apache.struts.action.ActionForm class, which provides the methods to get
and set data fields with methods to validate the data. The relation between user requests, the
action class to be invoked, the ActionForm class to be used, and the next possible views are
defined in the struts-config.xml file using appropriate mappings.
View
The view represents a JSP or HTML page. The presentation semantics are encapsulated within aview. There is no business logic available in the view.
Recommended