Anda di halaman 1dari 38

Seminar Report on

J2EE

AT
Naresh i Technologies
Hyderabad

Under the guidance of


Mr. L. N. Rao
CO-ORDINATOR

SUBMITTED BY

MANJIT SAHU Roll # 200710224

OF THE DEPARTMENT OF
INFORMATION TECHNOLOGY

For the partial fulfillment of


BACHELOR OF TECHNOLOGY

NATIONAL INSTITUTE OF SCIENCE & TECHNOLOGY


PALUR HILLS, BERHAMPUR, ORISSA – 761008
ACKNOWLEDGEMENT

I express my deep sense of gratitude to, Mr. L. N. Rao Advisor for his valuable
guidance and constant unfailing encouragement for completing the summer course.

I would like to thank Dr.Sudhir Panigrahy for their help and support for doing my
summer training at Naresh i Technology, Hyderabad.

Finally, I would like to thank the Mr. Sangram Mudali for providing us proper
environment or the completion of the report.

MANJIT SAHU

i
ABSTRACT
The Java 2 Platform, Enterprise Edition (J2EE) defines the standard for developing
multitier enterprise applications. The J2EE platform simplifies enterprise applications
by basing them on standardized, modular components, by providing a complete set of
services to those components, and by handling many details of application behavior
automatically, without complex programming. The J2EE platform takes advantage of
many features of the Java 2 Platform, Standard Edition (J2SE), such as "Write Once,
Run Anywhere" portability, JDBC API for database access, CORBA technology for
interaction with existing enterprise resources, and a security model that protects data
even in internet applications. Building on this base, the Java 2 Platform, Enterprise
Edition adds full support for Enterprise JavaBeans components, Java Servlets API,
Java Server Pages and XML technology. The J2EE standard includes complete
specifications and compliance tests to ensure portability of applications across the
wide range of existing enterprise systems capable of supporting the J2EE platform. In
addition, the J2EE specification now ensures Web services interoperability through
support for the WS-I Basic Profile.

ii
TABLE OF CONTENTS

ACKNOWLEDGEMENT..............................................................................................i
Abstract..........................................................................................................................ii
Table of contents...........................................................................................................iii
1. Introduction................................................................................................................5
2. SALIENT features.....................................................................................................6
Figure 2.1 Enterprise Application Model.........................................................................7
3. NOMENCLATURE STANDARDS & SPECIFICATIONS ..............................10
4. INTRODUCTION TO JDBC..................................................................................11
4.1 JDBC API Overview .........................................................................................11
4.2 Advantages of JDBC Technology .....................................................................11
4.3 KEY FEATURES..............................................................................................12
4.4. JDBC ARCHITECTURE..................................................................................12
Figure 4.1 JDBC Architecture1......................................................................................13
Figure 4.2 JDBC Architecture 2.....................................................................................14
4.5 Two-tier and Three-tier Models.........................................................................15
4.6 JDBC Driver Type.............................................................................................16
5. JAVA SERVLET TECHNOLOGY.........................................................................18
Figure 5.1 Client – servlet interaction..........................................................................19
5.1 The Benefits of Servlets.....................................................................................19
5.2 Servlet Application Architecture........................................................................21
Figure 5.2 the Servlet Application Architecture...........................................................21
5.3 Lifecycle of a servlet..........................................................................................22
Figure 5.3 Servlet Lifecycle........................................................................................22
5.4 Servlet sample code............................................................................................23
6. JAVA SERVER PAGES..........................................................................................24
6.1 About jsp............................................................................................................25
Figure 6.1 Generating Dynamic Content with JSP.........................................................26
6.2 The Problem with Servlets.................................................................................26
6.3 Advantages Of JSP.............................................................................................26
6.4 The Anatomy of a JSP Page...............................................................................27
7. ENTERPRISE JAVA BEAN...................................................................................28
7.1Benefits of Enterprise Beans...............................................................................28
7.2 Use of Enterprise Beans.....................................................................................28
8. AJAX........................................................................................................................30
8.1 INTRODUCTION..............................................................................................30
8.2 Traditional vs Ajax technology..........................................................................30
Figure 8.1 Traditional Web application communication flow.............................30
Figure 8.2 Ajax-style communication flow..................................................................31
8.3 Overview of XHRs.............................................................................................31
9. XML.........................................................................................................................33
9.1 Introduction........................................................................................................33
10. Struts .....................................................................................................................34
10.1 Design goals and overview..............................................................................34
11. CONCLUSION......................................................................................................36
REFERENCES............................................................................................................37

iii
iv
J2EE

1. INTRODUCTION

Today's enterprises gain competitive advantage by quickly developing and deploying


custom applications that provide unique business services. Whether they're internal
applications for employee productivity, or Internet applications for specialized
customer or vendor services, quick development and deployment are key to success.

Portability and scalability are also important for long term viability. Enterprise
applications must scale from small working prototypes and test cases to complete 24x
7, enterprise-wide services, accessible by tens, hundreds, or even thousands of clients
simultaneously.

However, multitier applications are hard to architect. They require bringing together a
variety of skill sets and resources, legacy data and legacy code. In today's
heterogeneous environment, enterprise applications have to integrate services from a
variety of vendors with a diverse set of application models and other standards.
Industry experience shows that integrating these resources can take up to 50% of
application development time.

As a single standard that can sit on top of a wide range of existing enterprise systems
-- database management systems, transaction monitors, naming and directory services,
and more -- the J2EE platform breaks the barriers inherent between current enterprise
systems. The unified J2EE standard wraps and embraces existing resources required
by multitier applications with a unified, component-based application model. This
enables the next generation of components, tools, systems, and applications for
solving the strategic requirements of the enterprise.

The J2EE specification also supports emerging Web Services technologies through
inclusion of the WS-I Basic Profile. WS-I Basic Profile compliance means that the
developers can build applications on the J2EE platform as Web services that
interoperate with Web services from non-J2EE compliant environments.

With simplicity, portability, scalability, and legacy integration, the J2EE platform is
the platform for enterprise solutions.
5
J2EE

2. SALIENT FEATURES

2.1 Enterprise Application Model

The Enterprise Java BluePrints for the J2EE platform describe the J2EE application
model and best practices for using the J2EE platform. Building on the J2SE platform,
the J2EE application model provides a simplified approach to developing highly
scalable and highly available internet or intranet based applications. Thanks to the
J2EE application model, maybe the most interesting thing about J2EE applications is
what they don't do. That is, various complexities inherent in enterprise applications --
transaction management, life-cycle management, resource pooling -- are built into the
platform and provided automatically to the components it supports. Component and
application developers are free to focus on specifics such as business logic and user
interfaces.

Another advantage of the J2EE platform is that the application model encapsulates the
layers of functionality in specific types of components. Business logic is encapsulated
in Enterprise JavaBeans (EJB) components. Client interaction can be presented
through plain HTML web pages, through web pages powered by applets, Java
Servlets, or Java Server Pages technology, or through stand-alone Java applications.
Components communicate transparently using various standards: HTML, XML,
HTTP, SSL, RMI, IIOP, and others. Reusable J2EE components mean competitive
choices for enterprise developers and IT organizations. The J2EE platform enables
them to assemble applications from a combination of standard, commercially
available components and their own custom components. From general business
application components to vertical market solutions, a range of standardized J2EE
functionality is available off the shelf.

This means that an e-commerce site could be built using a combination of off-the-
shelf EJB components for shopping cart behaviors, modified EJB components for
specialized customer services, and completely customized layouts using Java Server
Pages technology that bring a unique look and feel to the site. This approach means
faster development time, better quality, maintainability and portability, and Web

6
J2EE

services interoperability across a range of enterprise platforms. The bottom line


benefits are increased programmer productivity, better strategic use of computing
resources, and greater return on an organization's technology investments.

Figure 2.1 Enterprise Application Model

2.2 Containers and Connectors: Hiding Complexity, Enhancing


Portability
The J2EE application model divides enterprise applications into three fundamental
parts: components, containers, and connectors. Components are the key focus of
application developers, while system vendors implement containers and connectors to
conceal complexity and promote portability. Containers intercede between clients and
components, providing services transparently to both, including transaction support
and resource pooling. Container mediation allows many component behaviors to be
specified at deployment time, rather than in program code.

7
J2EE

Connectors sit beneath the J2EE platform, defining a portable service API that
communicates with existing enterprise vendor offerings. Connectors promote
flexibility by enabling a variety of implementations of specific services. In particular,
connectors implementing pluggable messaging contracts enable bidirectional
communication between J2EE components and enterprise systems.

2.3 Flexible User Interaction


The J2EE platform provides choices for graphical user interfaces across a company's
intranet or on the World Wide Web. Clients can run on desktops, laptops, PDAs, cell
phones, and other devices. Pure client-side user interfaces can use standard HTML
and Java applets. Support for simple HTML means quicker prototypes, and support
for a broader range of clients. Additionally, the J2EE platform supports automatic
download of the Java Plug-in to add applet support where it's lacking. The J2EE
platform also supports stand-alone Java application clients.
For server-side generation of dynamic content, the J2EE platform supports two types
of web component technologies: Java Servlets and JavaServer Pages (JSP). Java
Servlets enable developers to easily implement server-side behaviors that take full
advantage of the power of the rich Java API. JavaServer Pages technology combines
the ubiquity of HTML with the power of server-side dynamic content generation. The
JSP 2.0 specification supports static templates, simplified access to Java objects, and
easy extensibility.

2.4 Enterprise JavaBeans Component Model


Enterprise JavaBeans (EJB) technology enables a simplified approach to multitier
application development, concealing application complexity and enabling the
component developer to focus on business logic.

EJB technology gives developers the ability to model the full range of objects useful
in the enterprise by defining several types of EJB components: session beans, entity
beans, message-driven beans. Session beans represent behaviors associated with client
sessions -- for example, a user purchase transaction on an e-commerce site. Session
beans can serve as Web service endpoints. Entity beans represent collections of data --

8
J2EE

such as rows in a relational database -- and encapsulate operations on the data they
represent. Entity beans are intended to be persistent, surviving as long as the data
they're associated with remains viable. Message-driven beans allow J2EE applications
to process messages asynchronously. A message-driven bean normally acts as a JMS
message listener, which is similar to an event listener except that it receives JMS
messages instead of events. The messages may be sent by any J2EE component--an
application client, another enterprise bean, or a Web component--or by a JMS
application or system that does not use J2EE technology.

2.5 Web Services Interoperability

The Java 2 Platform, Enterprise Edition version 1.4 is the most complete Web
services platform ever. The platform features Web services support through the new
JAX-RPC 1.1 API, which provides service endpoints based on servlets and enterprise
beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL
and SOAP protocols. The J2EE 1.4 platform also supports the Web Services for J2EE
specification, which defines deployment requirements for Web services and utilizes
the JAX-RPC programming model. In addition to numerous Web services APIs, the
J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means
that in addition to platform independence and complete Web services support, the
J2EE 1.4 platform offers platform Web services interoperability.

2.6 Expediting Development and Deployment


Based on these flexible component configurations, the J2EE application model means
quicker development, easier customization and greater ability to deploy powerful
enterprise applications. And, because it's based on the Java programming language,
this model enables all J2EE applications to achieve all the benefits of Java
technology: scalability, portability, and programming ease.

9
J2EE

3. NOMENCLATURE STANDARDS &


SPECIFICATIONS

The platform was known as Java 2 Platform, Enterprise Edition or J2EE until the
name was changed to Java EE in version 5. The current version is called Java EE 6.

Java EE is defined by its specification. As with other Java Community process


specifications, providers must meet certain conformance requirements in order to
declare their products as Java EE compliant.

Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web
services, XML, etc., and defines how to coordinate them. Java EE also features some
specifications unique to Java EE for components. These include Enterprise
JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification),
JavaServer Pages and several web service technologies. This allows developers to
create enterprise applications that are portable and scalable, and that integrate with
legacy technologies. A Java EE application server can handle transactions, security,
scalability, concurrency and management of the components that are deployed to it, in
order to enable developers to concentrate more on the business logic of the
components rather than on infrastructure and integration tasks.

10
J2EE

4. INTRODUCTION TO JDBC

The Java Database Connectivity (JDBC) API is the industry standard for database-
independent connectivity between the Java programming language and a wide range
of databases. SQL databases and other tabular data sources, such as spreadsheets or
flat files. The JDBC API provides a call-level API for SQL-based database access.

JDBC technology allows you to use the Java programming language to exploit "Write
Once, Run Anywhere" capabilities for applications that require access to enterprise
data. With a JDBC technology-enabled driver, you can connect all corporate data
even in a heterogeneous environment.

4.1 JDBC API Overview


The JDBC API makes it possible to do three things:

• Establish a connection with a database or access any tabular data source


• Send SQL statements
• Process the results

4.2 Advantages of JDBC Technology


4.2.1 Leverage Existing Enterprise Data
With JDBC technology, businesses are not locked in any proprietary
architecture, and can continue to use their installed databases and access
information easily -- even if it is stored on different database management
systems.
4.2.2 Simplified Enterprise Development
The combination of the Java API and the JDBC API makes application
development easy and economical. JDBC hides the complexity of many data
access tasks, doing most of the "heavy lifting"for the programmer behind the
scenes. The JDBC API is simple to learn, easy to deploy, and inexpensive to
maintain.

11
J2EE

4.3 KEY FEATURES


Full Access to Metadata
The JDBC API provides metadata access that enables the development of
sophisticated applications that need to understand the underlying facilities and
capabilities of a specific database connection.
No Installation
A pure JDBC technology-based driver does not require special installation; it is
automatically downloaded as part of the applet that makes the JDBC calls.
Database Connection Identified by URL
JDBC technology exploits the advantages of Internet-standard URLs to identify
database connections. The JDBC API includes an even better way to identify and
connect to a data source, using a DataSource object, that makes code even more
portable and easier to maintain.

4.4. JDBC ARCHITECTURE

The JDBC API contains two major sets of interfaces: the first is the JDBC API for
application writers, and the second is the lower-level JDBC driver API for driver
writers. JDBC technology drivers fit into one of four categories. Applications and
applets can access databases via the JDBC API using pure Java JDBC technology-
based drivers, as shown in this figure:

12
J2EE

Figure 4.1 JDBC Architecture1

Left side, Type 4: Direct-to-Database Pure Java Driver


This style of driver converts JDBC calls into the network protocol used directly by
DBMSs, allowing a direct call from the client machine to the DBMS server and
providing a practical solution for intranet access.

Right side, Type 3: Pure Java Driver for Database Middleware


This style of driver translates JDBC calls into the middleware vendor's protocol,
which is then translated to a DBMS protocol by a middleware server. The middleware
provides connectivity to many different databases.

The graphic below illustrates JDBC connectivity using ODBC drivers and existing
database client libraries.

13
J2EE

Figure 4.2 JDBC Architecture 2


Left side, Type 1: JDBC-ODBC Bridge plus ODBC Driver
This combination provides JDBC access via ODBC drivers. ODBC binary code -- and
in many cases, database client code -- must be loaded on each client machine that uses
a JDBC-ODBC Bridge. Sun provides a JDBC-ODBC Bridge driver, which is
appropriate for experimental use and for situations in which no other driver is
available.

Right side, Type 2: A native API partly Java technology-enabled driver


This type of driver converts JDBC calls into calls on the client API for Oracle,
Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of
driver requires that some binary code be loaded on each client machine.

14
J2EE

4.5 Two-tier and Three-tier Models

The JDBC API supports both two-tier and three-tier models for database access.

In the two-tier model, a Java applet or application talks directly to the database. This
requires a JDBC driver that can communicate with the particular database
management system being accessed. A user's SQL statements are delivered to the
database, and the results of those statements are sent back to the user. The database
may be located on another machine to which the user is connected via a network. This
is referred to as a client/server configuration, with the user's machine as the client,
and the machine housing the database as the server. The network can be an intranet,
which, for example, connects employees within a corporation, or it can be the
Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then
send SQL statements to the database. The database processes the SQL statements and
sends the results back to the middle tier, which then sends them to the user. MIS
directors find the three-tier model very attractive because the middle tier makes it
possible to maintain control over access and the kinds of updates that can be made to
corporate data. Another advantage is that when there is a middle tier, the user can
employ an easy-to-use higher-level API which is translated by the middle tier into the
appropriate low-level calls. Finally, in many cases the three-tier architecture can
provide performance advantages.

15
J2EE

Until now the middle tier has typically been written in languages such as C or C++,
which offer fast performance. However, with the introduction of optimizing compilers
that translate Java bytecode into efficient machine-specific code, it is becoming
practical to implement the middle tier in Java. This is a big plus, making it possible to
take advantage of Java's robustness, multithreading, and security features. JDBC is
important to allow database access from a Java middle tier.

4.6 JDBC Driver Type

The JDBC drivers that we are aware of at this time fit into one of four categories:

1. JDBC-ODBC bridge plus ODBC driver: The JavaSoft bridge product provides
JDBC access via ODBC drivers. Note that ODBC binary code, and in many
cases database client code, must be loaded on each client machine that uses
this driver. As a result, this kind of driver is most appropriate on a corporate
network where client installations are not a major problem, or for application
server code written in Java in a three-tier architecture.
2. Native-API partly-Java driver: This kind of driver converts JDBC calls into
calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS.

16
J2EE

Note that, like the bridge driver, this style of driver requires that some binary
code be loaded on each client machine.
3. JDBC-Net pure Java driver: This driver translates JDBC calls into a DBMS-
independent net protocol which is then translated to a DBMS protocol by a
server. This net server middleware is able to connect its pure Java clients to
many different databases. The specific protocol used depends on the vendor.
In general, this is the most flexible JDBC alternative. It is likely that all
vendors of this solution will provide products suitable for Intranet use. In
order for these products to also support Internet access, they must handle the
additional requirements for security, access through firewalls, and so on, that
the Web imposes. Several vendors are adding JDBC drivers to their existing
database middleware products.
4. Native-protocol pure Java driver: This kind of driver converts JDBC calls into
the network protocol used by DBMSs directly. This allows a direct call from
the client machine to the DBMS server and is a practical solution for Intranet
access. Since many of these protocols are proprietary, the database vendors
themselves will be the primary source, and several database vendors have
these in progress. Eventually, we expect that driver categories 3 and 4 will be
the preferred way to access databases from JDBC. Driver categories 1 and 2
are interim solutions where direct pure Java drivers are not yet available.

The following chart shows the four categories and their properties:

DRIVER CATEGORY ALL JAVA? NET PROTOCOL


1 - JDBC-OCBC Bridge No Direct
2 - Native API as basis No Direct
3 - JDBC-Net Yes Requires Connector
4 - Native protocol as basis Yes Direct

17
J2EE

5. JAVA SERVLET TECHNOLOGY

Java Servlet technology provides a basic mechanism for generating dynamic Web
content. Think of them as Java applets for servers. Servlets were developed as an
improvement over CGI scripts, which are generally platform−specific, and are limited
in their ability to support rich interaction. Because servlets are based on the Java
programming language, they offer several benefits over CGI, including portability,
flexibility, and programming ease. In addition, they provide better performance
because they are persistent a servlet needs to be loaded into memory and initialized
just once. It's then available to serve any user request.

Like all J2EE components, servlets run in a container implemented by the J2EE
platform provider. The container manages a servlet's interaction with its client and
provides a rich environment for the servlet to use to access various services based on
Java technology. A servlet container implements all of the Java 2 Platform, Standard
Edition APIs. This makes a variety of technologies based on the Java programming
language available to servlets, including JDBC, Java Naming and Directory Interface,
RMI, JavaBeans, and others.
The container can also implement features that allow servlets to share information
about a particular client and session, overcoming the obstacles generally presented by
the stateless HTTP protocol. The flexibility of servlets is enabled through the servlet
API, which implements a mechanism for more complex interaction with the
requesting client than can CGI. Various servlet methods provide information to the
servlet and allow it to respond. Because of the object−oriented programming model,
items key to servlet behaviors are provided as objects with a well−defined API.

18
J2EE

Figure 5.1 Client – servlet interaction

5.1 The Benefits of Servlets


When it first emerged, this great thing we call the Internet consisted of only static
contents written using Hypertext Markup Language (HTML). At that time, anyone
who could author HTML pages was considered an Internet expert. This did not last
long, however. Soon dynamic web contents were made possible through the Common
Gateway Interface (CGI) technology. CGI enables the web server to call an external
program and pass HTTP request information to that external program to process the
request. The response from the external program is then passed back to the web
server, which forwards it to the client browser. CGI programs can be written in any
language that can be called by the web server. Over the course of time, Perl became
the most popular language to write CGI programs.

As the Internet became more and more popular, however, the number of users visiting
a popular web site increased exponentially, and it became apparent that CGI had
failed to deliver scalable Internet applications. The flaw in CGI is that each client
request makes the web server spawn a new process of the requested CGI program. As
we all know, process creation is an expensive operation that consumes a lot of CPU
cycles and computer memory. Gradually, new and better technologies will replace
CGI as the main technology for web application development. The world has
witnessed the following technologies trying to dominate web development:

19
J2EE

• ColdFusion. Allaire's ColdFusion provides HTML-like custom tags that can be


used to perform a number of operations, especially querying a database. This
technology had its glamorous time in the history of the World Wide Web as the main
technology for web application programming. Its glorious time has since gone with
the invention of other technologies.
• Server-side JavaScript (SSJS). SSJS is an extension of the JavaScript language,
the scripting language that still rules client-side web programming. SSJS can access
Java classes deployed at the server side using the LiveWire technology from
Netscape.
• PHP. PHP is an exciting open-source technology that has matured in recent years.
The technology provides easy web application development with its session
management and includes some built-in functionality, such as file upload. The
number of programmers embracing PHP as their technology of choice has risen
sharply in recent years.
• Servlet. The servlet technology was introduced by Sun Microsystems in 1996.

• Java Server Pages (JSP). JSP is an extension of the servlet technology. This, too,
is the center of attention in this book.

In the past, ASP and servlet/JSP have been the main technologies used in web
application development. With the release of ASP.NET, it is not hard to predict that
this technology will become the servlet/JSP's main competitor. ASP (and ASP.NET)
and servlet/JSP each have their own fans, and it is not easy to predict which one will
come out the winner. The most likely outcome is that neither will be an absolute
winner that corners the market; instead the technologies will probably run head-to-
head in the coming years. Servlet (and JSP) offers the following benefits that are not
necessarily available in other technologies:
• Performance. The performance of servlets is superior to CGI because there is no
process creation for each client request. Instead, each request is handled by the servlet
container process. After a servlet is finished processing a request, it stays resident in
memory, waiting for another request.
• Portability. Similar to other Java technologies, servlet applications are portable.
You can move them to other operating systems without serious hassles.

20
J2EE

• Rapid development cycle. As a Java technology, servlets have access to the rich
Java library, which helps speed up the development process.
• Robustness. Servlets are managed by the Java Virtual Machine. As such, you don't
need to worry about memory leak or garbage collection, which helps you write robust
applications.
• Widespread acceptance. Java is a widely accepted technology. This means that
numerous vendors work on Java-based technologies. One of the advantages of this
widespread acceptance is that you can easily find and purchase components that suit
your needs, which saves precious development time.

5.2 Servlet Application Architecture


A servlet is a Java class that can be loaded dynamically into and run by a special web
server. This servlet-aware web server is called a servlet container, which also was
called a servlet engine in the early days of the servlet technology. Servlets interact
with clients via a request-response model based on HTTP. Because servlet technology
works on top of HTTP, a servlet container must support HTTP as the protocol for
client requests and server responses. However, a servlet container also can support
similar protocols, such as HTTPS (HTTP over SSL) for secure transactions.

Figure 5.2 the Servlet Application Architecture


In a JSP application, the servlet container is replaced by a JSP container. Both the
servlet container and the JSP container often are referred to as the web container or
servlet/JSP container, especially if a web application consists of both servlets and JSP
pages.

21
J2EE

5.3 Lifecycle of a servlet

The servlet lifecycle consists of the following steps:

1. The servlet class is loaded by the Web container during start-up.


2. The Web container calls the init() method. This method initializes the servlet
and must be called before the servlet can service any requests. In the entire life
of a servlet, the init() method is called only once.
3. After initialization, the servlet can service client requests. Each request is
serviced in its own separate thread. The Web container calls the service()
method of the servlet for every request. The service() method determines the
kind of request being made and dispatches it to an appropriate method to
handle the request. The developer of the servlet must provide an
implementation for these methods. If a request for a method that is not
implemented by the servlet is made, the method of the parent class is called,
typically resulting in an error being returned to the requester. Finally, the Web
container calls the destroy() method that takes the servlet out of service. The
destroy() method, like init(), is called only once in the lifecycle of a servlet.

Figure 5.3 Servlet Lifecycle

22
J2EE

5.4 Servlet sample code


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class TestingServlet extends HttpServlet {


public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Testing Center");
out.println("</BODY>");
out.println("</HTML>");
}

The clientside browser will have the html page of code


<html>
<body bgcolor="white">
<h1>Good evening!</h1>
Welcome to our site, open 24 hours a day.
</body>
</html>

23
J2EE

6. JAVA SERVER PAGES


In late 1999, Sun Microsystems added a new element to the collection of Enterprise
Java tools: JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets
and are designed to increase the efficiency in which programmers, and even
nonprogrammers, can create web content. This book is primarily about JavaServer
Pages, covering the latest version of this technology, JSP 1.2, as well as the related
JSP Standard Tag Library (JSTL) Version 1.0. It also covers other J2EE technologies,
such as servlets and JDBC, with focus on how to combine them with JSP in the most
efficient way.

JavaServer Pages technology builds on Java Servlet technology to simplify the


development of dynamic Web content. JSP supports a page−based metaphor that
conveniently separates dynamic and static Web content; the JSP page defines a static
HTML template, with embedded calls to code written in the Java programming
language to fill in dynamic portions of the page. JSP pages contain four kinds of
elements, each with a specific role in the presentation of dynamic content. Text
elements are normally content formatted through standard HTML or XML. These
represent the static portion of the page.
1. Directives are instructions to the JSP processor. A JSP container processes
these directives when compiling the page into an efficient executable form.
2. Tags invoke JavaBeans to generate dynamic content or perform other
computations. Tag libraries are a powerful feature of JSPs used to encapsulate
specific functionality invoked via HTML tags. These allow the JSP
_language_ to be easily extended in a portable fashion. For example, tag
libraries can be implemented to support embedded database queries for an
application.
3. Scripting elements may be declarations, scriptlets, or expressions. Like tags,
scripting elements can be used to perform computations to generate dynamic
content. They are useful when standard tags are inappropriate or have not been
defined.
4. The combination of these four elements makes it easy to generate Web pages
for client browsers. Because JSP is based on servlets, users benefit from the
application support and other features built into Web application containers.
24
J2EE

These include portability, access to common services, the ability to maintain


state and client−access information via common APIs, and other servlet
benefits.
The advantage of the JSP model is that Web designers need not be familiar with the
Java programming language to create sophisticated JSP pages. JSP is designed to
enable Web authoring tools to automatically generate tags, scripting elements, and
other HTML, and to enable the incorporation of dynamic elements by means of
familiar drag−and−drop authoring techniques. Programmers can focus on providing
JavaBeans and custom tags for use by the Web designer; organizations can even
acquire custom behaviors from third−party developers. This supports one of the
higher goals of J2EE, separating the skill sets required to develop and assemble
complex applications into more logical roles. Using J2EE technology and tools,
Web−page designers and content providers can focus on presenting the best look and
feel possible, without programming, while application programmers can develop
complex behind−the−scenes behavior, without having to be user−interface experts.

6.1 About jsp


Dynamic content. Unlike a plain HTML page, which contains static content that
always remains the same, a JSP page can change its content based on any number of
variable items, including the identity of the user, the user's browser type, information
provided by the user, and selections made by the user. As you'll see later in the book,
this functionality is key to web applications such as online shopping and employee
directories, as well as for personalized and internationalized content. A JSP page
contains standard markup language elements, such as HTML tags, just like aregular
web page. However, a JSP page also contains special JSP elements that allow the
server to insert dynamic content in the page. JSP elements can be used for a variety of
purposes, such as retrieving information from a database or registering user
references. When a user asks for a JSP page, the server executes the JSP elements,
merges the results with the static parts of the page, and sends the dynamically
composed page back to the browser.

25
J2EE

Figure 6.1 Generating Dynamic Content with JSP


6.2 The Problem with Servlets
• Thorough Java programming knowledge is needed to develop and maintain all
aspects of the application, since the processing code and the HTML elements
are lumped together.
• Changing the look and feel of the application, or adding support for a new
type of client (such as a WML client), requires the servlet code to be updated
and recompiled.
• It's hard to take advantage of web-page development tools when designing the
application interface. If such tools are used to develop the web page layout,
the generated HTML must then be manually embedded into the servlet code, a
process which is time consuming, error prone, and extremely boring.
6.3 Advantages Of JSP

1. The JSP technology is platform independent, in its dynamic web pages, its web
servers, and its underlying server components. That is, JSP pages perform perfectly
without any hassle on any platform, run on any web server, and web-enabled
application server. The JSP pages can be accessed from any web server.

2. The JSP technology emphasizes the use of reusable components. These


components can be combined or manipulated towards developing more purposeful
components and page design. This definitely reduces development time apart from the
At development time, JSPs are very different from Servlets, however, they are
precompiled into Servlets at run time and executed by a JSP engine which is installed
on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.

26
J2EE

6.4 The Anatomy of a JSP Page


A JSP page is simply a regular web page with JSP elements for generating the parts
that differ for each request

Everything in the page that isn't a JSP element is called template text. Template text
can be any text: HTML, WML, XML, or even plain text. Since HTML is by far the
most common web-page language in use today, most of the descriptions and examples
in this book use HTML, but keep in mind that JSP has no dependency on HTML; it
can be used with any markup language. Template text is always passed straight
through to the browser.
27
J2EE

When a JSP page request is processed, the template text and dynamic content
generated by the JSP elements are merged, and the result is sent as the response to the
browser

7. ENTERPRISE JAVA BEAN


Written in the Java™ programming language, an enterprise bean is a server-side
component that encapsulates the business logic of an application. The business logic
is the code that fulfills the purpose of the application. In an inventory control
application, for example, the enterprise beans might implement the business logic in
methods called checkInventoryLevel and orderProduct. By invoking these methods,
remote clients can access the inventory services provided by the application.

7.1Benefits of Enterprise Beans


For several reasons, enterprise beans simplify the development of large, distributed
applications. First, because the EJB container provides system-level services to
enterprise beans, the bean developer can concentrate on solving business problems.
The EJB container not the bean developer is responsible for system-level services
such as transaction management and security authorization. Second, because the
beans and not the clients contain the application’s business logic, the client developer
can focus on the presentation of the client. The client developer does not have to code
the routines that implement business rules or access databases. As a result, the clients
are thinner, a benefit that is particularlyimportant for clients that run on small devices.
Third, because enterprise beans are portable components, the application assembler
can build new applications from existing beans. These applications can run on any
compliant J2EE server.

7.2 Use of Enterprise Beans


One should consider using enterprise beans if the application has any of these
requirements:

28
J2EE

• The application must be scalable. To accommodate a growing number of


users, you may need to distribute an application’s components across multiple
machines. Not only can the enterprise beans of an application run on different
machines, but their location will remain transparent to the clients.
• Transactions are required to ensure data integrity. Enterprise beans support
transactions, the mechanisms that manage the concurrent access of shared
objects.

29
J2EE

8. AJAX
8.1 INTRODUCTION

Ajax (Asynchronous JavaScript and XML) encompasses much more than the
technologies that make up this catchy acronym. The general term Ajax describes the
usage of various Web technologies to transform the sluggish batch submission of
traditional Web applications into a highly responsive near desktop-software-like user
experience. However, such a dramatic improvement does come with the price of a
significant rise in programming complexity, increased network concerns, and new
user experience design challenges. For now, let’s avoid most of those details, as is
appropriate in an introduction, and begin with an overview of the concepts behind
Ajax illustrated by an example. Details of the example will then be presented hinting
at future complexity. The chapter then concludes with a brief discussion of the
historical rise and potential effects of Ajax upon Web development.

8.2 Traditional vs Ajax technology

Figure 8.1 Traditional Web application communication flow

30
J2EE

Figure 8.2 Ajax-style communication flow

8.3 Overview of XHRs

At the heart of Ajax is the XHR object. A bit misnamed, this object provides
generalized HTTP or HTTPS access for client-side scripting and is not limited to just
making requests or using XML, as its name would suggest. The facility was first
implemented in Internet Explorer 5 for Windows to support the development of
Microsoft Outlook Web Access for Exchange 2000, and this object has come to be
widely supported in all major desktop browsers. Native implementations can be found
in Safari 1.2+, Mozilla 1+, Netscape 7+, Opera 8+, and Internet Explorer 7+.
ActiveX-based implementations are found in Internet Explorer 5, 5.5, and 6. Browser
support for XHRs is summarized in

Property or Method Description


readyState Integer indicating the state of
the request, either:
0 (uninitialized)
1 (loading)
2 (response headers received)
3 (some response body
received)
4 (request complete)
Onreadystatechange Function to call whenever the

31
J2EE

readyState changes
Status HTTP status code returned by
the server
(e.g., “200, 404, etc.”)
statusText Full status HTTP status line
returned by the server (e.g.,
“OK, No Content, etc.”)
responseText Full response from the server
as a string
responseXML A Document object
representing the server’s
response
parsed as an XML document
abort() Cancels an
asynchronous HTTP
abort() Cancels an asynchronous HTTP
request
getAllResponseHeaders() Returns a string containing all
the HTTP headers the server
sent in its response. Each
header is a name/value pair
separated by a colon and
header lines are separated by a
carriage return/linefeed pair

32
J2EE

9. XML

9.1 Introduction

XML stands for the eXtensible Markup Language. It is a new markup language,
developed by the W3C (World Wide Web Consortium), mainly to overcome
limitations in HTML. The W3C is the organization in charge of the development and
maintenance of most.
HTML is an immensely popular markup language. According to some studies there
are 800 million Web pages, all based on HTML. HTML is supported by thousands of
applications including browsers, editors, email software, databases, contact managers,
and more.
Originally, the Web was a solution to publish scientific documents. Today it has
grown into a full-fledged medium, equal to print and TV. More importantly, the Web
is an interactive medium because it supports applications such as online shops,
electronic banking, and trading and forums.
To accommodate this phenomenal popularity, HTML has been extended over the
years. Many new tags have been introduced. The first version of HTML had a dozen
tags; the latest version (HTML 4.0) is close to 100 tags .
Furthermore, a large set of supporting technologies also has been introduced:
JavaScript, Java, Flash, CGI, ASP, streaming media, MP3, and more. Some of these
technologies were developed by the W3C whereas others were introduced by vendors.
However, everything is not rosy with HTML. It has grown into a complex language.
At almost 100 tags, it is definitively not a small language. The combinations of tags
are almost endless and the result of a particular combination of tags might be different
from one browser to another.
Finally, despite all these tags already included in HTML, more are needed. Electronic
commerce applications need tags for product references, prices, name, addresses, and
more. Streaming needs tags to control the flow of images and sound. Search engines
need more precise tags for keywords and description. Security needs tags for signing.
The list of applications that need new HTML tags is almost endless.

33
J2EE

10. STRUTS

Web applications differ from conventional websites in that web applications can
create a dynamic response. Many websites deliver only static pages. A web
application can interact with databases and business logic engines to customize a
response.

Web applications based on JavaServer Pages sometimes commingle database code,


page design code, and control flow code. In practice, we find that unless these
concerns are separated, larger applications become difficult to maintain.

One way to separate concerns in a software application is to use a Model-View-


Controller (MVC) architecture. The Model represents the business or database code,
the View represents the page design code, and the Controller represents the
navigational code. The Struts framework is designed to help developers create web
applications that utilize a MVC architecture.

The framework provides three key components:

• A "request" handler provided by the application developer that is mapped to a


standard URI.
• A "response" handler that transfers control to another resource which
completes the response.
• A tag library that helps developers create interactive form-based applications
with server pages.

The framework's architecture and tags are buzzword compliant. Struts works well
with conventional REST applications and with nouveau technologies like SOAP and
AJAX.

10.1 Design goals and overview

In a standard Java EE web application, the client will typically submit information to
the server via a web form. The information is then either handed over to a Java
Servlet that processes it, interacts with a database and produces an HTML-formatted

34
J2EE

response, or it is given to a JavaServer Pages (JSP) document that intermingles


HTML and Java code to achieve the same result. Both approaches are often
considered inadequate for large projects because they mix application logic with
presentation and make maintenance difficult.

The goal of Struts is to cleanly separate the model (application logic that interacts
with a database) from the view (HTML pages presented to the client) and the
controller (instance that passes information between view and model). Struts provides
the controller (a servlet known as ActionServlet) and facilitates the writing of
templates for the view or presentation layer (typically in JSP, but XML/XSLT and
Velocity are also supported). The web application programmer is responsible for
writing the model code, and for creating a central configuration file struts-
config.xml that binds together model, view and controller.

Requests from the client are sent to the controller in the form of "Actions" defined in
the configuration file; if the controller receives such a request it calls the
corresponding Action class that interacts with the application-specific model code.
The model code returns an "ActionForward", a string telling the controller what
output page to send to the client. Information is passed between model and view in the
form of special JavaBeans. A powerful custom tag library allows it to read and write
the content of these beans from the presentation layer without the need for any
embedded Java code.

Struts also supports internationalization by web forms, and includes a template


mechanism called "Tiles" that (for instance) allows the presentation layer to be
composed from independent header, footer, and content components.

35
J2EE

11. CONCLUSION

The pace of business is getting faster and faster, with a greater need to compete and
sustain a market. In this age of e−commerce, e−business, e−tailing, and other e's,
"traditional" system development just doesn't cut it anymore. Java Platform,
Enterprise Edition or Java EE is a widely used platform for server programming in
the Java programming language. TheJava platform (Enterprise Edition) differs from
the Java Standard Edition Platform (Java SE) in that it adds libraries which provide
functionality to deploy fault-tolerant, distributed, multi-tier Java software, based
largely on modular components running on an application server.
The Java platform comes in three flavours: Standard Edition, Enterprise Edition and
Macro Edition. The Enterprise Edition (J2EE) builds the Standard Edition & includes
number of technologies, such as Enterprise JavaBeans(EJB), Servlet and JavaServer
Pages, used for building enterprise server side- applications.

36
J2EE

REFERENCES

[1] Enterprise JavaBeans, Third Edition , Richard Monson-Haefel

[2] JavaServer Pages, Hans Bergsten


[3] www.java.sun.com

37

Anda mungkin juga menyukai