J2EE ARCHITECTURE


The Java™ 2 Platform, Enterprise Edition (J2EE) provides a standard for developing multitier, enterprise services.

The economy and technology of today have intensified the need for faster, more efficient, and larger-scale information management solutions. The J2EE specification satisfies these challenges by providing a programming model that improves development productivity, standardizes the platform for hosting enterprise applications, and ensures portability of developed applications with an extensive test suite.

J2EE architecture supports component-based development of multi-tier enterprise applications. A J2EE application system typically includes the following tiers:

  • Client tier: In the client tier, Web components, such as Servlets and JavaServer Pages (JSPs), or standalone Java applications provide a dynamic interface to the middle tier.
  • Middle tier: In the server tier, or middle tier, enterprise beans and Web Services encapsulate reusable, distributable business logic for the application. These server-tier components are contained on a J2EE Application Server, which provides the platform for these components to perform actions and store data.
  • Enterprise data tier: In the data tier, the enterprise's data is stored and persisted, typically in a relational database.

J2EE applications are comprised of components, containers, and services. Components are application-level components. Web components, such as Servlets and JSPs, provide dynamic responses to requests from a Web page. EJB components contain server-side business logic for enterprise applications. Web and EJB component containers host services that support Web and EJB modules.

Java 2 EE Web Arch

J2EE implements the Presentation Layer with Servlets and, more recently, Java provides the option to generate webpages with dynamic content using JavaServer Pages (JSP). Servlets/JSP generate webpages with dynamic content (typically originating from the database). They also parse webpages submitted from the client and pass them to Enterprise JavaBeans for handling. Servlets and JSPs run inside a Web Server.

J2EE implements the Business Logic layer with Enterprise JavaBeans (EJB). Enterprise JavaBeans are responsible for logic like validation and calculations as well as provided data access (e.g. database I/O) for the application. Enterprise JavaBeans run inside an Application Sever.

Under J2EE, EJBs access a database through one of two means:

  • using a JDBC interface which requires a lower level of coding and/or
  • using SQLJ which provides a higher level interface to the database

In addition to these components for web application, J2EE provides for access by non-web clients to the business logic layer. A standalone Java application (IIOP client) can access an EJB directly using J2EE's Remote Method Invocation (RMI) API.

OBJECT RELATION MAPPING IN HIBERNATE


ORM - Object Relation Mapping. Almost all contemporary databases are relational and based on SQL language. Most programs using them are created in an object way. So some kind of incoherence appears at the meeting point of a database and software. We need some appropriate tools to translate data from relational language into an object language and the other way round.
Service of JDBC is extremely troublesome while dealing with more complex applications.

ORM deals with following tasks:
Hibernate is currently one of the most popular ORM solutions.Its popularity and effectiveness were proved by the fact that e.g. implementation of CMP in EJB3 on JBoss server is based on Hibernate. What is more, a lot of solutions were copied during designing EJB3 specification.
Other, common solutions ORM include: CMP, JDO. Hibernate, as opposed to them, is not a standard but a concrete solution.

Its main advantage is:
- lightness � it is no need to use special containers, it is enough to attach an appropriate library. One can also use it to both: web and client applications. There is no need to generate manually an additional code. As opposed to e.g. JDO, Hibernate requires only presence of configuration files. Additional classes used by it are generated during performing a task.

Persistence


Meaning of the persistence is one of the most imporant thing in application development. Nowdays almost all applications require persistent data so it is very important for an system to preserve data entered by users even if the machine was powered off. Persistance in Java ( Hibernate ) is storing data in a relational databse using SQL.

Relational technology provides a way of sharing data among different aplications or among technologies that form part of the same application. Relational technology is a common denominator of many different technology platforms and systems so it is't specific to a particular application.

SQL in Hibernate

SQL in Hibernate During working with an SQL database in a Java application , the Java code issues SQL statements to the databese using Java DataBase Connectivity API (JDBC). JDBC API is used to bind arguments to query parameters for example: to retrieve values from the result set. But these are low-level data access tasks, and what we really like to do is write code that saves and retrives complex objects, to and from the database.


HIBERNATE'S ARCHITECTURE

Hibernate is based on similar ideas and patterns like other ORM(Object-relational mapping)
solutions (JDO, CMP).

Basic classes used while working with Hibernate are:
- SessionFactory,
- Session,
- Transaction

SessionFactory
An object of this class provides with
Session objects. It contains information concerning mapped objects a configuration is being loaded during its formation.An application has usually one object of this class it can be managed by e.g. Spring.

Session
one of the most important objects of Hibernate and one of the most troublesome at the beginning. An object of this class represents a unit of work with a database, it usually equals one connection (Connection) with a database. It represents a unit of work with Hibernate. It equals e.g. PersistenceManager in CMP. All persistent objects are attributed to some definite session and any attempt to modify them or even ( sometimes) acces to them results in an exception.


Session is opened by
SessionFactory.newSession()

and closed by
session.close()

One session should match a logic part of the program an execution of a task. Sometimes ( but not always!) it can be a transaction. While dealing with www applications
session-per-request

Transaction
- equals one database transaction. It is connected with a concrete session and is made by means of
Transaction tx = session.beginTransaction( );

We can cancel it or confirm
tx.commit(); tx.rollback();

model is very common and easy to implement. Then the session is opened at the beginning of the processing of a claim and closed at the end. The easiest way to do it is by means of the filter. This model can be a bit troublesome if we store some persistent objects in a html sesion ( that is when we use e.g. JSF, Struts)


HIBERNATE - Introduction to Hibernate

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects.
HIBERNATE - Overview of Hibernate
Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...).
Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application startup time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files.
Typical Hibernate code

sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Customer newCustomer = new Customer();newCustomer.setName("New Customer");newCustomer.setAddress("Address of New Customer");newCustomer.setEmailId("NewCustomer@NewCustomer.com");
session.save(newCustomer);tx.commit();
session.close();

First step is hibernate application is to retrieve Hibernate Session; Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.After specifying transaction boundaries, application can make use of persistent java objects and use session for persisting to the databases.
HIBERNATE - Main Features
The most important Hibernate's feature is mapping from Java classes to database tables (and from Java data types to SQL data types), but also to provides data query ( and retrieval facilities ).It is important that Hibernate generates the SQL calls and relieves keeping the application portable to all SQL databases, with database portability delivered at very little performance overhead.This feature can significialy reduce development time that programmer would have to spent with manual data handling in SQL and JDBC.Reasuming Hibernate allows to create high-performance database applications with Java much faster and easier. Thanks to transparent persistence for Plain Old Java Objects (POJOs) all you need to do is build a simple POJO, next create XML mapping file that will describe relationship between the databse and the class attributes and at the end call Hibernate API's to specify the operationsYou can use Hibernate as in standalone Java applications or as in Java EE applications using servlets or EJB session beans.


JAVA SERVER PAGE (JSP)


Java Server Pages (JSP) is server side java technology that allows software developers to create HTML, XML, or other document types, in response to a web client request to a Java Web Application container (server). Architecturally, JSP may be viewed as a high-level abstraction of Java servelets. JSP pages are loaded in the server and operated from a structured special installed Java server packet called a J2EE Web Application often packaged as a .war or .ear file archive. dynamically generated web pages, with

The technology allows Java code and certain pre-defined actions to be embedded into static page content and compiled on the server at runtime of each page request. Both the Java Server (J2EE specification) and the page scripts and/or extended customised programming added operate by (in the runtime context of being loaded programs used) a special pre-installed base program called a vertual machine(VM) that integrates with the host operating system, this type being the Java (JVM). vertual machine

JSP syntax has two basic forms, scriptlet and markup though fundamentally the page is either HTML or XML markup. Scriptlet tagging (called Scriptlet Elements)(delimited) blocks of code with the markup are not effectively markup and allows any java server relevant API (e.g. the servers running binaries themselves or database connections API or java mail API) or more specialist JSP API language code to be embedded in an HTML or XML page provided the correct declarations in the JSP file and file extension of the page are used. Scriptlet blocks do not require to be completed in the block itself only the last line of the block itself being completed syntactically correctly as a statement is required, it can be completed in a later block. This system of split inline coding sections is called step over scripting because it can wrap around the static markup by stepping over it. At runtime (during a client request) the code is compiled and evaluated, but compilation of the code generally only occurs when a change to the code of the file occurs. The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. JVM operated Tag libraries provide a platform independent way of extending the capabilities of a web server. Note that not all company makes of Java servers are J2EE specification compliant.

LIFE CYCLE OF AN APPLET

An applet can react to major events in the following ways:
  • It can initialize itself.
  • It can start running.
  • It can stop running.
  • It can perform a final cleanup, in preparation for being unloaded.

This section introduces a new applet, Simple, that uses all of these methods. Unlike Java applications, applets do not need to implement a main method.

The following is the source code for the Simple applet. This applet displays a descriptive string whenever it encounters a major milestone in its life, such as when the user first visits the page the applet is on.


import java.applet.Applet;
import java.awt.Graphics;

//No need to extend JApplet, since we don't add any components;
//we just paint.
public class Simple extends Applet {

StringBuffer buffer;

public void init() {
buffer = new StringBuffer();
addItem("initializing... ");
}

public void start() {
addItem("starting... ");
}

public void stop() {
addItem("stopping... ");
}

public void destroy() {
addItem("preparing for unloading...");
}

private void addItem(String newWord) {
System.out.println(newWord);
buffer.append(newWord);
repaint();
}

public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);

//Draw the current string inside the rectangle.
g.drawString(buffer.toString(), 5, 15);
}
}
Loading the Applet

As a result of the applet being loaded, you should see the text "initializing... starting...". When an applet is loaded, here's what happens:

  • An instance of the applet's controlling class (an Applet subclass) is created.
  • The applet initializes itself.
  • The applet starts running.
Leaving and Returning to the Applet's Page

When the user leaves the page, for example, to go to another page, the browser stops and destroys the applet. The state of the applet is not preserved. When the user returns to the page, the browser intializes and starts a new instance of the applet.


Reloading the Applet

When you refresh or reload a browser page, the current instance of the applet is stopped and destroyed and a new instance is created.




JAVA APPLET


Getting Started with applets


The HelloWorld applet shown next is a Java class that displays the string "Hello World".

Following is the source code for the HelloWorld applet:

import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;

public class HelloWorld extends JApplet {
//Called when this applet is loaded into the browser.
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}

An applet such as this is typically managed and run by the Java Plug-in software in the browser.





JAVA ENTERPRISE EDITION


J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing typical of large enterprises. Sun Microsystems (together with industry partners such as IBM) designed J2EE to simplify application development in a thin client tiered environment. J2EE simplifies application development and decreases the need for programming and programmer training by creating standardized, reusable modular components and by enabling the tier to handle many aspects of programming automatically.

J2EE is a platform-independent, Java-centric environment for developing, building and deploying Web-based enterprise applications online.J2EE includes many components of the Java Standard Edition (J2SE).The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications.

J2EE includes many components of the Java 2 Platform, Standard Edition (J2SE):

  • The Java Development Kit (JDK) is included as the core language package.
  • Write Once Run Anywhere technology is included to ensure portability.
  • Support is provided for Common Object Request Broker Architecture (CORBA), a predecessor of Enterprise JavaBeans (EJB), so that Java objects can communicate with CORBA objects both locally and over a network through its interface broker.
  • Java Database Connectivity 2.0 (JDBC), the Java equivalent to Open Database Connectivity (ODBC), is included as the standard interface for Java databases.
  • A security model is included to protect data both locally and in Web-based applications.

J2EE also includes a number of components added to the J2SE model, such as the following:

  • Full support is included for Enterprise JavaBeans. EJB is a server-based technology for the delivery of program components in an enterprise environment. It supports the Extensible Markup Language (XML) and has enhanced deployment and security features.
  • The Java Servlet API (application programming interface) enhances consistency for developers without requiring a graphical user interface (GUI).
  • Java Server Pages (JSP) is the Java equivalent to Microsoft's Active Server Pages (ASP) and is used for dynamic Web-enabled data access and manipulation.

The J2EE architecture consists of four major elements:

  • The J2EE Application Programming Model is the standard programming model used to facilitate the development of multi-tier, thin client applications.
  • The J2EE Platform includes necessary policies and APIs such as the Java servlets and Java Message Service (JMS).
  • The J2EE Compatibility Test Suite ensures that J2EE products are compatible with the platform standards.
  • The J2EE Reference Implementation explains J2EE capabilities and provides its operational definition.

JAVA SERVLETS


Common Gateway Interface (CGI) was one of the first tools for creating webpages with dynamic content. In fact, from reading many early Internet books or articles, one would have the impression that CGI was the only way to create dynamic content. Over time, vendors introduced alternative methods for creating dynamic content. Netscape introduced server-side JavaScript while Microsoft introducted Active Server Pages (ASP).

In 1997, Sun introduced Servlets to create webpages with dynamic content. Servlets are used within a web server (in place of CGI scripts) and run inside the Java Virtual Machine (JVM) on the server. Unlike applets, they do not require support for Java in the web browser. Servlets can be run on all major web servers (either directly or via widely available third-party plug-ins).

In creating webpages with dynamic content, Servlets also provide an infrastructure to parse/decode the user-submitted HTML form, handle cookies, etc. As such, the Servlet can manage all the presentation aspects of the web application.

Servlets can access database directly (as might be appropriate for a simple web application) or Servlets can derive their dynamic content via a sepearate business layer running on an application server (as would be appropriate for larger web applications).

Since Servlets follow the standard Sun-defined API, Servlet application code is portable across web servers.

Servlet Code Sample

The following Servlet code sample generates a webpage which generates a webpage that says "Welcome back, username" (where username is the current user).

import java.io.*;
import javax.sertlet.*;
import javax.servlet.*;
public class WelcomeUser extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
res.setContentType(“text/html”);
PrintWriter out = res.getWriter();
    out.println(“”);
out.println(“”);
out.println(“

Welcome back,”);
out.print(“String user = ”);
out.println(“(String) session.getAttribute(‘user’)”);
out.println(user);
out.println(“

”);
out.println(“”);
out.println(“”);
}
}