Sie sind auf Seite 1von 15

Java EE Related Technologies

Chapter 2: Java EE Related Technologies Syllabus: 1. Java Database Connectivity 2. Servlets 3. JavaServer Pages 4. Java Server Faces 5. JavaMail 6. Enterprise JavaBeans 7. Hibernate 8. Seam 9. Java EE Connector Architecture 10. Web Services 11. Strut 12. Spring 13. JAAS 14. 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 with databases for storing application specific information. For example, Search engines use database for storing information about the web pages; Job portals use database for storing information about the candidates and employers, accessing the site for searching and advertising jobs on the Internet. However, interacting with database requires database connectivity. This can be achieved by using the ODBC driver, which is used with Java Database Connectivity (JDBC) to interact with databases 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 JDBC API, 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 referred as 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 the Java programming language. Therefore, we can say that JDBC is a standard API to access enterprise data in a relational database. The JDBC API allows Jaya programs to execute SQL statements 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 not specify any specific DBMS for the requested data; rather they can use the drivers to target a specific database for the user requests. JDBC provides the following characteristics, which makes it more 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 for representing the driver services. JDBC can be used as a higher level API for the application programmers. The JDBC API specification is used as an interface for the application and the DBMS. JDBC specification provides JDBC API for Java applications. The JDBC call to a Java application 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 SQL queries to a database. The JDBC drivers are responsible for querying the database for the

Java EE Related Technologies


SQL queries and retrieving the results. Components of JDBC JDBC has four main components through which it communicates with a database. These components are: 1. The JDBC API The JDBC API provides various methods and interfaces for easy and effective 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 DriverManager DriverManager 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 loaded drivers when a new connection to the database is established. In addition, it is used to make 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. JDBC comes with a Test Suite that is used for evaluating the JDBC drivers for its compatibility with Java EE. The JDBC test suite is used to test the operations being performed by JDBC drivers. 4. The JDBC-ODBC BridgeThe JDBC-ODBC Bridge is used to connect database drivers to the database. This driver translates JDBC method calls to ODBC function calls. The bridge is used 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 the specifications 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.0 Optional 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. The JDBC 3.0 specification provides performance optimization features and improves the features of connection pooling and statement pooling, and also provides a migration path to Sun Microsystems connector architecture. JDBC 4.0- Provides following advance features: o Auto loading of the Driver interface o Connection management o ROWID data type support o Annotation in SQL queries o National Character Set Conversion Support o Enhancement to exception handling o 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 provides classes and interfaces to handle database specific calls from users. Some of the important classes and interfaces are: Connection DatabaseMetaData PreparedStatement

Java EE Related Technologies


Statement Driver CallableStatement ResultSet DriverManager ResultSetMetaData SqlData Blob Clob 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-1 demonstrates 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 be programmed 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 done dynamically at runtime. This ensures that the Java application is vendor independent. Therefore, if we 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 JDBC drivers 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 whereas others 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 use to 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-ODBC bridge) Type-2 Driver This driver is a Partly Java and Partly Native code driver Type-3 Driver This is a Pure Java driver that uses a middleware driver to connect to a database Type-4 Driver This is a Pure Java driver and is directly connected to a database

Java EE Related Technologies


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 driver implementation. The JDBC-ODBC Bridge provides the access to the database by using the ODBC drivers. 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 to communicate with the respective database. As shown in the figure Java Application is programmed to JDBC API and will make a request to JDBC-ODBC bridge driver i.e. JDBC call, where JDBC-ODBC bridge 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 into action 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 Application in JDBC standards. This type of driver is generally used in the development and testing phases of Java 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 in production environment. In case a database does not have any other JDBC driver implementations, then only we should use this driver in the production environment. Describing Type-2 Driver (Java to Native API)

Java EE Related Technologies


Type-2 driver converts JDBC call into DB vendor specific native call in a client machine. In other words, 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-tier architecture 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 is programmed using JDBC API. These JDBC calls (programs written by using JDBC API) are converted into database specific native calls in the client machine and the request is then dispatched to the database specific native libraries. These native libraries present in the client are intelligent 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 DBMS vendor. 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 use Type-2 drivers with client-side applications, since the database specific native libraries for the client 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 drivers We 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 different platforms (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 to communicate 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.

Java EE Related Technologies


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 server specific net protocol calls (network calls), which are then translated into database server specific calls by the middleware server. Type-3 drivers follow 3-tier architecture model, as shown in Figure 2-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 and translates 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 specific calls. This type of drivers are named as net-protocol fully Java technology-enabled driver, or simply 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 this architecture more useful in enterprise applications. Type-3 driver is recommended to be used with applets 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 not required 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 of network 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 specific understandable 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 a suitable JDBC driver to communicate with a database.

Java EE Related Technologies


Describing the Type-4 Driver (Java to Database protocol) The Type-4 driver is a pure Java driver, which implements the database protocol to interact directly with a database. This type of drivers does not require any native database libraries to retrieve the records from the database. This type of drivers translates JDBC calls into Database specific 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 is generally known as thin driver. The Type-4 driver uses data base specific proprietary protocols for communication. Generally, this type of drivers are implemented by DBMS vendors, since the protocol used here are proprietary. You can use Type-4 drivers when you want an auto downloadable option for the client-side applications. 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 is DBMS 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, platformindependent, and senwr-independent standards to develop Web applications in Java. The Servlet technology 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 enhances the functionality of the Web server. A Servlet is secure and portable as it runs on Java Virtual

Java EE Related Technologies


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 dynamic Web applications. They can run on any Java-enabled platform and are usually designed to process HTTP requests, such as GET, and POST. Servlet API includes two packages: 1. javax.servlet and 2. 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 in and provides an insight to some of the mechanisms available to a developer for sharing server-side resources. The primary reason why Servlets and JSP outperform traditional CGI is the Servlet life-cycle. The Servlets follow a three-phase life namely: (ISD) 1. Initialization, 2. Service, and 3. Destruction. This three-phase lifecycle is opposed to the single-phase life-cycle. Among the three phases, the Servlet 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 initialization of 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-cycle represents 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 and 2. 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 instance of 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 of the 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 might have 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 for servicing requests. The resources are then readily used during the service phase and then can be

Java EE Related Technologies


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 on the Web is primarily accessed via the Hyper Text Transfer Protocol (HTTP). A basic Servlet knows nothing 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 not only 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. It is not called again for other user request. Therefore, it is used for one-time initializations only, just as 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 database settings, password files, server-specific performance parameters, hit count files, or serialized cookie data from previous requests. Initialization parameters let the Servlet to deploy (for example the 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 of ServletConfig, 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 form that has no METHOD specified. The POST request results from an HTML form that specifically lists POST as the METHOD. For example: <html> <form name=myform method=post> 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

Java EE Related Technologies


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 it perhaps 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 count on 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 their state to disk periodically.

Hibernate Hibernate provides a framework for mapping an object-oriented domain model to a relational database. 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 handling resultsets. 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 be used both standalone Java applications and in Java EE applications using Servlets or EJB session beans. Introduction to Hibernate Hibernate is a lightweight Object/Relational mapping (ORM), which is a technique for mapping an object 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 write sophisticated query by using Hibernate Query Language (HQL) that reduces the time spent in handling data by using SQL and JDBC. It relieves the developer from 95 percent of a common data persistence 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 XML mapping file that describes relationship between the database and the class attributes by using

10

Java EE Related Technologies


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 works efficiently with applications that use Swings, Servlets, and EJB Session beans. It does not require developers to implement interfaces or extend classes to be persistent. It has extensive support of Java collections API (Map, Set, List, SortedMap, SortedSet, and Collection). Why Hibernate? Hibernate is a technology that provides solution for object relational mapping and persistence management. The reasons for using Hibernate are as follows: Supports natural Object-oriented Programming model, such as inheritance, polymorphism, composition, abstraction, and the Java collections framework Provides developers with persistence feature and a code generation library, CGLIB to extend Java classes and implement Java interfaces at runtime environment. If any changes are made to objects associated with a transaction, they are automatically detected and propagated to the database. This saves the time spent in extra coding for bytecode processing. 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 multicriteria search and dynamic queries much easier. Queries may be polymorphic and can use any abstract superclass or interface Provides 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 by using 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 as inheritance, 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 Native o Identity o Sequence o Increment o HI/L0 algorithm o UUID algorithm Provides hibernate Multi level Cache Architecture for thread safety and continuous data access. Provides features, such as Lazy initialization and Eager or Batch fetching for improving the performance 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 JINDI o Stateful Session bean or in a servlet HttpSession with load balancing can include Session o JDBC connections may be provided by application data source o 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 makes use 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 a connection for accessing relational database. It uses all types of database driver that are supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with application servers.

11

Java EE Related Technologies


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 and relational database. The syntax of HQL is very similar to SQL. It has a rich and powerful Objectoriented query language available with the Hibernate object/relational mapping (ORM). The term ORM refers to the technique of mapping objects and databases. The data from Object-oriented systems 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 query and executes it, if HQL queries are used in the application. HQL uses classes and properties instead of 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 Query By Example (QBE) using Criteria API and the Native SQL queries. It even supports projection/aggregation and subselects. HQL is used for retrieving objects from database through O/R mapping. Thus, HQL provides the following: Applying restrictions to properties of objects Ordering the results returned by a query Pagination of results Aggregation using group by, having clauses Joins User-defined functions Subqueries

12

Java EE Related Technologies


Struts Struts 2 is a Web application framework based on Model-View-Controller (MVC), and is used to build high-performance and business-oriented Web applications. Before the introduction of Struts, there was no standard component framework to develop Java EE Web applications. The mechanism 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 the model, 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 is released to the public domain free of charge. The Struts 2 framework is designed to help developers in creating Web applications based on MVC architecture. Since Struts 2 is based on the MVC 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 into components 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 for new 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, and so on, to enable rapid development of Web applications. Therefore, it became necessary to modify the 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 WebWork framework was released. WebWork includes new ideas, concepts and functionality with the original Struts 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 2 architecture 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.

13

Java EE Related Technologies


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 the interface provided by the view, instantiates an object of the suitable action class, and executes 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 code returned by the action class. The view presents the user interface. The view queries about the state of the model to show 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, and Struts tags. All framework components work together in a standard manner. The architecture of Struts 2-based application defines the relationship and interaction between these framework components. 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 components created 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 in the 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 access point for presentation-tier request handling, the singleton pattern provides a single instance of an object. 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 this task. 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 around the business logic and interact with the model of the application. They are basically responsible for executing the business service according to user requests. Model

14

Java EE Related Technologies


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 a view. There is no business logic available in the view.

15

Das könnte Ihnen auch gefallen