0% found this document useful (0 votes)
115 views

Unit 1: Enterprise Computing in Java

This document provides an introduction to enterprise computing in Java, including J2EE (Java 2 Enterprise Edition). It discusses the key components and technologies of J2EE such as EJBs, JSPs, servlets, and design patterns like MVC. It also summarizes the servlet architecture and lifecycle. The document aims to explain the basics of building J2EE applications and developing multi-tier enterprise systems using Java technologies.

Uploaded by

Ashish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Unit 1: Enterprise Computing in Java

This document provides an introduction to enterprise computing in Java, including J2EE (Java 2 Enterprise Edition). It discusses the key components and technologies of J2EE such as EJBs, JSPs, servlets, and design patterns like MVC. It also summarizes the servlet architecture and lifecycle. The document aims to explain the basics of building J2EE applications and developing multi-tier enterprise systems using Java technologies.

Uploaded by

Ashish Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

H.

Enterprise Computing in Java


ST
UNIT 1
Introduction to J2EE and building J2EE application:

INTRODUCTION:

• "Java" refers to both a language and a platform.


• The Java programming language is a high-level, object-oriented language that has a
particular syntax and style.

• A Java platform is a particular environment in which Java programming language


applications run.

• The runtime and libraries that comprise the platform are based on the Java language
and come in 4 flavors:

• Java SE (Standard Edition): A good mix of general purpose libraries including JDBC (Java
Database Connectivity), JNDI (Java Naming Directory Interface), RMI (Remove Method
Invocation), AWT, and Swing.

• Java EE (Enterprise Edition): Includes Java Standard Edition plus other Java technologies
including JavaMail, Activation, JAXB (Java API for XML Binding), Servlets, JSF (Java Server
Faces), JMS (Java Messaging Service), EJB (Enterprise Java Beans), and others.

• Java ME (Micro Edition): Formerly J2ME. It includes most of Java SE and some additional
APIs for handheld devices.

• JavaFX

All Java platforms consist of a JVM and an API.

Platform introduced June, 1999

• J2SE – Java 2 Standard Edition

Java for the desktop / workstation

http://java.sun.com/j2se

1
H.T

• J2ME – Java 2 Micro Edition

Java for the consumer device

http://java.sun.com/j2me

• J2EE - Java 2 Enterprise Edition

Java for the server

http://java.sun.com/j2ee

J2EE(Java 2 Enterprise Edition):


The Java 2 platform, Enterprise Edition reduces the cost and complexity of developing ...
multi-tier services, resulting in services that can be rapidly deployed and easily
enhanced“

• It is a public specification that embodies several technologies like JavaMail, Activation,


JAXB (Java API for XML Binding), Servlets, JSF (Java Server Faces), JMS (Java Messaging
Service), EJB (Enterprise Java Beans), and others.

• J2EE defines a model for developing multi-tier, web based, enterprise applications with
distributed components.

J2EE Provides:

• Enabling technology

• Standards based application model

• A common architecture that provides key common functionality:

– Security

– Session Management

Scalability

2
H.T

• High availability

• Scalability

• Integration with existing systems

• Freedom to choose vendors of application servers, tools, components

• Multi-platform

J2EE Technologies:
• Java Servlets

• JSP

• EJB

3
H.T

• JMS

• JDBC

• JNDI

• JTA / JTS

• JavaMail

• JAAS

XML

J2EE Components:

Application Servers:
Today, enterprise applications use the multi-tier model

4
H.T

Two main architectures when developing web applications in Java:


• The first architecture utilizes servlets and JSP in the middle tier to serve clients and
process the business logic.

Servlet/ JSP Application Architecture Small to medium-size applications use this design
model

• The second architecture includes the use of J2EE server and Enterprise
JavaBeans (EJB) and this is especially useful for large enterprise
applications that need scalability.

5
H.T

Application component:
 JSPs, servlets and EJBs are application components

Multi-tier typical application:

Web-centric application:

6
H.T

Business-to-business:

MVC Architecture:
• The MVC (Model-View-Controller) architecture is a way of decomposing an application
into three parts: the model, the view and the controller.

• It was originally applied in the graphical user interaction model of input, processing and
output.

• The Model represents the structure of the data in the application, as well as application-
specific operations on those data.

7
H.T

• A View (of which there may be many) presents data in some form to a user, in the
context of some application function.

• A Controller translates
es user actions (mouse motions, keystrokes, words spoken, etc.)
and user input into application function calls on the model, and selects the appropriate
View based on user preferences and Model state.

MVC Structure for J2EE:

• A model represents an application’s data and contains the logic for accessing and
manipulating that data. Any data that is part of the persistent state of the application
should reside in the model objects.

• The services that a model exposes must be generic enough to support a variety of
clients.

• By glancing at the model's public method list, it should be easy to understand how to
control the model's behavior. A model groups related data and operations for providing
a specific service; these group of operations wrap and abstract the functionality of the
business process being modeled.

8
H.T

• A model’s interface exposes methods for accessing and updating the state of the model
and for executing complex processes encapsulated inside the model.

• The view is responsible for rendering the state of the model.

• The presentation semantics are encapsulated within the view, therefore model data
can be adapted for several different kinds of clients.

• The view modifies itself when a change in the model is communicated to the view.

A view forwards user input to the controller

• The controller is responsible for intercepting and translating user input into actions to
be performed
ed by the model.

The controller is responsible for selecting the next view based on user input and the outcome of
model operations

Details of MVC Design Pattern:

• Name (essence of the pattern)

– Model View Controller MVC

• Context (where does this problem occur)


occu

– MVC is an architectural pattern that is used when developing interactive


application such as a shopping cart on the Internet.

• Problem (definition of the reoccurring difficulty)

User interfaces change often, especially on the internet where look


look-and-feel is a competitive
issue. Also, the same information is presented in different ways. The core business logic and
data is stable

• Solution (how do you solve the problem)

9
H.T

– Use the software engineering principle of “separation of concerns” to divide the


application into three areas:

• Model encapsulates the core data and functionality

• View encapsulates the presentation of the data there can be many views
of the common data

Controller accepts input from the user and makes request from the model for the data to
produce a new view.

Advantages of MVC:

• Separating Model from View (that is, separating data representation from presentation)

- easy to add multiple data presentations for

the same data,

-facilitates adding new types of data

presentation as technology develops.

-Model and View components can vary

independently enhancing maintainability,

extensibility, and testability.

Advantages of MVC design Pattern:

• Separating Controller from View (application behavior from presentation)

- permits run-time selection of appropriate

Views based on workflow, user preferences,

or Model state.

• Separating Controller from Model (application behavior from data representation)

- allows configurable mapping of user actions

on the Controller to application functions on

the Model.

10
H.T

Introduction to Servlets and its Life Cycle:


servlet is a Java technology based web component, managed by a container, that generates
dynamic content.
A servlet can be considered as a tiny Java program which processes user request and generates
dynamic content.
There are many other alternatives like php, asp .net or CGI, for developing dynamic web sites.
Benefit of using servlets over other technologies is servlets are developed in Java, so it comes
with all benefits of Java language and it is platform independent.

Following are the some advantages of using servlets.


(1) They are generally much faster than CGI scripts.
(2) They use a standard API that is supported by many web servers.
(3) They have all the advantages of the Java programming language, including
ease of development and platform independence.
(4) They can access the large set of APIs available for the Java platform

What is a Servlet Container?

Servlet container (also known as servlet engine) is a runtime environment, which


implements servlet API and manages life cycle of servlet components.
Container is responsible for instantiating, invoking, and destroying servlet components.
One example of container is Apache Tomcat which is an opensource container.

The Servlet API:

The servlet API provides the interfaces and classes that support servlets. These interfaces and
classes are grouped into two packages: javax.servlet, and javax.servlet.http.

S e r v le t C o n fi g

S er v le t G e n e r i c S e r vl e t H tt p S e r v l e t

S e r v l et R e q u es t H t tp S e r v l e tR e q u e s t

S e r v l e tR e s p o n s e H t tp S e r v l e tR e s p o n s e

ja v a x .s e r v l e t.* ja v a x .s e r v l e t.h tt p . *
11
H.T

Servlet Life Cycle:

• The life cycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following
steps.

• If an instance of the servlet does not exist, the Web container

– Loads the servlet class.

– Creates an instance of the servlet class.

– Initializes the servlet instance by calling the init method. Initialization is covered
in Initializing a Servlet.

• Invokes the service method, passing a request and response object.

• If the container needs to remove the servlet, it finalizes the servlet by calling the
servlet's destroy method.

The life cycle of a servlet can be categorized into four parts:

• Loading and Instantiation: The servlet container loads the servlet during startup or when
the first request is made. The loading of the servlet depends on the attribute <load-on-
startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the
servlet is load with loading of the container otherwise it load when the first request
comes for service. After loading of the servlet, the container creates the instances of the
servlet.

• Initialization: After creating the instances, the servlet container calls the init() method
and passes the servlet initialization parameters to the init() method. The init() must be
called by the servlet container before the servlet can service any request. The
initialization parameters persist untill the servlet is destroyed. The init() method is called
only once throughout the life cycle of the servlet.
The servlet will be available for service if it is loaded successfully otherwise the servlet
container unloads the servlet.

• Servicing the Request: After successfully completing the initialization process, the
servlet will be available for service. Servlet creates seperate threads for each request.
The sevlet container calls the service() method for servicing any request. The service()
method determines the kind of request and calls the appropriate method (doGet() or
doPost()) for handling the request and sends response to the client using the methods
of the response object.
12
H.T

• Destroying the Servlet: If the servlet is no longer needed for servicing any request, the
servlet container calls the destroy() method . Like the init() method this method is also
called only once throughout the life cycle of the servlet. Calling the destroy() method
indicates to the servlet container not to sent the any request for service an and the
servlet releases all the resources associated with it. Java Virtual Machine claims for the
memory associated with the resources for garbage collection.

Things we should know….

• init

Executed once when the servlet is first loaded.

Not called for each request.

• Service

Called in a new thread by server for each request.

Dispatches to doGet, doPost, etc.

Do not override this method!

• doGet, doPost, doBlah

Handles GET, POST, etc. requests.

13
H.T

Override these to provide desired behavior.

• destroy

Called when server deletes servlet instance.

Not called after each request.

Why Java Servlets Instead of CGI:


CGI

• Efficient, Convenient, Powerful, Portable, Secure, Inexpensive

– Lightweight threads instead of OS threads created

– Single copy of code brought into memory for all threads versus per thread

– Data (session state) can be stored across threads within servlet container

– Java is portable and secure

– Requires little expense once servlet container integrated with web server

• Java Servlet Objects on Server Side

• Managed by Servlet Container

– Loads/unloads servlets

– Directs requests to servlets

• Request → doGet()

• Each request is run as its own thread

Web App with Servlets:

14
H.T

1. Subclass off HttpServlet

2. Override doGet(....) method

3. HttpServletRequest

– getParameter("paramName")

4. HttpServletResponse

– set Content Type

– get PrintWriter

– send text to client via PrintWriter

5. Don't use instance variables

Problems with CGI-Perl


Perl Interface:
Interface

What is CGI?
• CGI is a way to interface programs, such as search engines, with Web servers.

15
H.T

• HTTP (Web) servers are designed primarily to serve up HTML documents. But CGI files
are not documents they are programs. Therefore, to store CGI programs most Web
servers use a special directory, commonly named cgi-bin.

• The Web server knows that files stored in the cgi-bin directory are to be executed rather
than simply sent to the user's Web browser for display.

• CGI programs can be written in a wide variety of languages, including DOS batch files,
BASIC, C, and scripting languages such as Perl.

Which programs qualify as a CGI program?

• A program must meet the following criteria to qualify as a CGI program

i) One should be able to type it directly by typing its name from the command line. A java
program does not qualify to be a CGI program because it cannot be executed in the Java
Virtual Machine unless we type “java program-name” in the command prompt.

ii) The program should generate a valid content-type header.

What can CGI programs not do?

A CGI program would not do the following:

• It does not interact with a user directly.

• It does not interact directly with a web browser or a graphical user interface. In other
words it does not display or retrieve information from menus, commands and other
interactive features of a client browser.

• It does not create graphics or windows by itself.

CGI-Perl Interface:
• 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.
Together the interface was popularly called the CGI-Perl Interface.

Advantages of CGI Programs


• CGI programs are portable and work on a wide variety of web servers and platforms.

16
H.T

• They are language independent and can be written in any language and work in a wide
variety of environments. Some of the programming languages used to write CGI scripts
are Perl, UNIX shell, C language, Visual Basic, Python, C# and Java.

• They provide simple interfaces for the client to interact with the web servers.

• They are scalable programs used to perform simple tasks in the application layer as well
as more complex tasks such as interacting with databases and shopping carts.

• The provide interactivity to a web application and enhance user experience.

• CGI programs are cost effective. By using them businesses can lower their development
and maintenance costs.

Disadvantages / Problems with CGI/Perl Interface


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 CGI programs are memory-intensive programs. Every time a request is made to a
server, it has to launch the CGI program. If they are written in a scripting language, the
interpreter for the scripting has to evaluate the entire script to execute the CGI program
each time the program is initiated. If the server has busy traffic, repeated client side
requests would consume a great deal of server resources and impact server
performance. This problem is minimized to some extent by CGI scripts written in a
compiled or interpreted language like C where there is no need for an interpreter to read
the CGI program code respectively.

• CGI programs are not easy to write. They require complex programming and designing
skills on the part of the web developers since a lot depends upon how they are
implemented in the server environment.

• If proper care is not taken, CGI programs may compromise server security.;

Most of the CGI programs are well-known, free and easily available. Their strengths and
vulnerabilities are known to most web-developers. This often results in their exploitation
and mis use.

Alternatives to CGI-Perl Interface

• The world has witnessed the following technologies trying to dominate web
development:

17
H.T

• ColdFusion. Allaire's ColdFusion provided HTML-like custom tags that can be used to
perform a number of operations, especially querying a database.

• 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.

• Servlet.

• JavaServer Pages (JSP). JSP is an extension of the servlet technology.

• Active Server Pages (ASP).

Generic and Http Servlet :


• Fundamentally, the job of a servlet is to process a request and to return a response.

• There are different APIs for manipulating the requests that the servlets are receiving
and for generating the response that the servlets are sending.

• Servlets are easy to work with because the container handles many functions.

• The container is also responsible for creating the request and response objects used by
methods like doGet() and doPost(). The container also controls the life cycle of a servlet
using methods declared in the Servlet interface.

Generic and Http Servlet


• GenericServlet implements the Servlet interface as well as the ServletConfig interface.
The service() method is its only abstract method.

• Finally, the HttpServlet abstract class extends GenericServlet and adds methods for
dealing with HTTP−specific requests. It has no abstract methods, but if you don't
override one of the basic methods it won't have any useful functionality and so is
declared to be an abstract class.

18
H.T

The Servlet Interface


• When a user makes a request for a servlet, the container creates an instance on the
servlet if one doesn't already exist.

• If there is an init() method, it will be called and must complete successfully before the
servlet sees any client requests.

• After the init() method returns, the container may or may not call the service() method
one or more times, passing in ServletRequest and ServletResponse objects as
arguments.

• Finally, the container can call the destroy() method to finalize the servlet and clean up
various resources.

Generic Servlet
• We can create a servlet by extending GenericServlet and overriding the service()
method.

• The GenericServlet class provides implementations of all of the methods in the


interfaces Servlet and ServletConfig except for service().

• GenericServlet also provides an implementation for the methods of the ServletConfig


interface.

• GenericServlet also contains two log() methods not specified in either the Servlet or the
ServletConfig interface. The first takes a string as its argument that will be the message
to be written to a servlet log file. The message will be tagged with a particular servlets
name in order to figure out which message belongs to which servlet. This method is
used with various life-cycle methods so that when init() or destroy() is called an
appropriate log entry is genetrated.

• The second version of the log() method takes an instance of Throwable as its second
argument.

• This signature of log() is implemented in GenericServlet to write the message you


specify as the first argument and to write a stack trace for the specified exception into
the log file.

HttpServlet

19
H.T

• GenericServlet may be directly extended by a servlet, although it is more common to


extend a protocol-specific subclass such as HttpServlet.

• HttpServlet provides an abstract class to be subclassed to create an HttpServlet suitable


for a Website.

• A subclass of HttpServlet must override atleast one method, usually one of these:

i) doGet() if the servlet supports Http Get requests.

ii) doPost(), for Http Post requests.

iii) doPut(), for Http Put requests.

iv) doDelete() for Http delete requests.

init() and destroy() to manage resources that are held for the life of the servlet.

• HttpServlet extends GenericServlet by adding methods to handle HTTP requests.

• GET and POST requests can be handled by using the HttpServlet methods doGet() and
doPost().

• The service methods doDelete(), doHead(), doOptions(), doPut(), and doTrace() are also
available to handle DELETE, HEAD, OPTIONS, PUT, and TRACE respectively.

• Each of these methods takes an HttpServletRequest object and an HttpServletResponse


object as arguments, and can throw a ServletException or an IOException.

• There are no abstract methods in the HttpServlet class. The service() method, which was
abstract in the parent class, is no longer abstract in HttpServlet.

20
H.T

Servlet Configuration:
Configuration
• The servlet specification allows you to configure your application. This can be done in
two ways:

i) Retrieve configuration information from the application web.xml file.

• For each servlet registered in the web.xml file, you have the option of specifying a set of
initial parameter name/value pairs that you can retrieve from inside the servlet.

• The following web.xml file contains a servlet called ConfigDemo whose class is na
named
ConfigDemoServlet.class.

• The servlet has two initial parameter name/value pairs. The first parameter is named
adminEmail and its value is [email protected]. The second parameter is
named adminContactNumber and the value for this parameter is 04298371237.
04298371237.

21
H.T

Method Summary:

Various Session Tracking Techniques:

Introduction
• The Hypertext Transfer Protocol (HTTP) is the network protocol that web servers and
client browsers use to communicate with each other.

• HTTP is the language of the web. HTTP connections are initiated by a client browser that
sends an HTTP request. The web server then responds with an HTTP response and
closes the connection.

• If the same client requests another resource from the server, it must open another HTTP
connection to the server.

• The server always closes the connection as soon as it sends the response, whether or
not the browser user needs some other resource from the server.

Putting this in a web perspective, because the web server always disconnects after it responds
to a request, the web server does not know whether a request comes from a user who has just
requested the first page or from a user who has requested nine other pages before. As such,
HTTP is said to be stateless

22
H.T

Session Management
• The statelessness of HTTP can have huge implications on web applications. Fortunately
there are ways to get around this, using techniques for remembering a user’s session.

• For Example: Once user has logged in, they do not need to log in again, the application
remembers them. This is called session management.

• Session management, also called session tracking, goes beyond simply remembering a
user who has successfully logged in. Anything that makes the application remember
information that has been entered or requested by the user can be considered session
management.

• Session management does not change the nature of HTTP statelessness—it simply
provides a way around it.

• By principle, you manage a user's session by performing the following to servlets/pages


that need to remember a user's state:

• When the user requests a servlet, in addition to sending the response, the servlet also
sends a token or an identifier.

• If the user does not come back with the next request for the same or a different servlet,
that is fine. If the user does come back, the token or identifier is sent back to the server.
Upon encountering the token, the next servlet should recognize the identifier and can
do a certain action based on the token. When the servlet responds to the request, it also
sends the same or a different token. This goes on and on with all the servlets that need
to remember a user's session.

Techniques for Session Management:


• We can use any of thefour techniques for session management. They operate based on
the same principle, although what is passed and how it is passed is different from one to
another. The techniques are as follows:

• URL rewriting

• Hidden fields

• Cookies

• Session objects

23
H.T

• Which technique you use depends on what you need to do in your application

URL Rewriting:
• With URL rewriting, you append a token or identifier to the URL of the next servlet or
the next resource. You can send parameter name/value pairs using the following
format:

• url?name1=value1&name2=value2&…

• A name and a value is separated using an equal sign (=); a parameter name/value pair is
separated from another parameter name/value pair using the ampersand (&).

• When the user clicks the hyperlink, the parameter name/value pairs will be passed to
the server. From a servlet, you can use the HttpServletRequest interface's getParameter
method to obtain a parameter value.

• For instance, to obtain the value of the second parameter, you write the following:

request.getParameter(name2);

• The use of URL rewriting is easy. When using this technique, however, you need to
consider several things:

• The number of characters that can be passed in a URL is limited. Typically, a browser can
pass up to 2,000 characters.

• The value that you pass can be seen in the URL. Sometimes this is not desirable. For
example, some people prefer their password not to appear on the URL.

• You need to encode certain characters—such as & and ? characters and white spaces—
that you append to a URL.

Hidden Fields:
• Another technique for managing user sessions is by passing a token as the value for an
HTML hidden field.

• Unlike the URL rewriting, the value does not show on the URL but can still be read by
viewing the HTML source code.

• Although this method also is easy to use, an HTML form is always required.

• For Ex:

24
H.T

• out.print("<INPUT TYPE=HIDDEN Name=id VALUE=" + id + ">");

• OR

• out.println("<FORM METHOD=POST ACTION=Page3Servlet>"); out.println("<INPUT


TYPE=HIDDEN NAME=firstName VALUE=\"" + StringUtil.encodeHtmlTag(firstName) +
"\">");

Cookies:
• The third technique that you can use to manage user sessions is by using cookies.

• A cookie is a small piece of information that is passed back and forth in the HTTP
request and response. Even though a cookie can be created on the client side using
some scripting language such as JavaScript, it is usually created by a server resource,
such as a servlet.

• The cookie sent by a servlet to the client will be passed back to the server when the
client requests another page from the same application.

• Cookies were first specified by Netscape and are now part of the Internet standard as
specified in RFC 2109: The HTTP State Management Mechanism. Cookies are transferred
to and from the client in the HTTP headers.

In servlet programming, a cookie is represented by the Cookie class in the javax.servlet.http


package.

• You can create a cookie by calling the Cookie class constructor and passing two String
objects: the name and value of the cookie. For instance, the following code creates a
cookie object called c1. The cookie has the name "myCookie" and a value of "secret":

• Cookie c1 = new Cookie("myCookie", "secret");

• You then can add the cookie to the HTTP response using the addCookie method of the
HttpServletResponse interface:

• response.addCookie(c1);

• Note that because cookies are carried in the request and response headers, you must
not add a cookie after an output has been written to the HttpServletResponse object.
Otherwise, an exception will be thrown.

25
H.T

Session Objects:
• The Session object, represented by the javax.servlet.http.HttpSession interface, is the
easiest to use and the most powerful technique for session management.

• For each user, the servlet can create an HttpSession object that is associated with that
user only and can only be accessed by that particular user.

• The HttpSession object acts like a Hashtable into which you can store any number of
key/object pairs. The HttpSession object is accessible from other servlets in the same
application. To retrieve an object previously stored, you need only to pass the key.

• An HttpSession object uses a cookie or URL rewriting to send a token to the client. If
cookies are used to convey session identifiers, the client browsers are required to
accept cookies.

Unlike previous techniques, however, the server does not send any value. What it sends is
simply a unique number called the session identifier. This session identifier is used to associate
a user with a Session object in the server. Therefore, if there are 10 simultaneous users, 10
Session objects will be created in the server and each user can access only his or her own
HttpSession

• There are four steps in session tracking using the HttpSession object:

• An HttpSession object is created by a servlet. A session identifier is generated for this


HttpSession object by the servlet container. This session identifier will be a random
number that is guaranteed to be unique. The HttpSession object then is stored in the
server and is associated with the generated session identifier. Also the programmer can
store values immediately after creating an HttpSession.

• In the response, the servlet sends the session identifier to the client browser.

• When the client browser requests another resource in the same application,, the
session identifier is sent back to the server and passed to next Servlet in the
javax.servlet.http.HttpServletRequest object.

• For Servlet2 to have access to the HttpSession object for this particular client, it uses the
getSession method of the javax.servlet.http.HttpServletRequest interface. This method
automatically retrieves the session identifier from the request and obtains the
HttpSession object associated with the session identifier.

26
H.T

Session Management:
• The first overload returns the current session associated with this request, or if the
request does not have a session identifier, it creates a new one.

• The second overload returns the HttpSession object associated with this request if there
is a valid session identifier in the request. If no valid session identifier is found in the
request, whether a new HttpSession object is created depends on the create value. If
the value is true, a new HttpSession object is created if no valid session identifier is
found in the request. Otherwise, the getSession method will return null.

Servlet context:
• In servlet programming, the servlet context is the environment where the servlet runs.

• The servlet container creates a ServletContext object that you can use to access
information about the servlet's environment.

• One can obtain a ServletContext object indirectly, from the ServletConfig object passed
by the servlet container to the servlet's init method.

• The ServletConfig interface has a method called getServletContext that returns the
ServletContext object. You then can use the ServletContext interface's various methods
to get the information you need

ServletContext Methods

27
H.T

Servlet Configuration: Explained above…

Servlet Collaboration:
• Sometimes servlets have to cooperate, usually by sharing some information.

• We call communication of this sort servlet collaboration.

• Collaborating servlets can pass the shared information directly from one servlet to
another through method invocations, as shown earlier.

• This approach requires each servlet to know the other servlets with which it is
collaborating—an unnecessary burden.

• One simple way for servlets to share information is by using Java’s system-wide
Properties list, found in the java.lang.System class.

• This Properties list holds the standard system properties, such as java.version and path
separator, but it can also hold application-specific properties.

• Servlets can use the properties list to hold the information they need to share.

• A servlet can add (or change) a property by calling:

• System.getProperties().put("key", "value");

• That servlet, or another servlet running in the same JVM, can later get the value of the
property by calling:

• String value = System.getProperty("key");

28
H.T

Enterprise Computing in Java


ND
UNIT 2
JSP Basics and Architecture:
• Today, the Java Enterprise APIs have expanded to encompass a number of areas: RMI
and CORBA for remote object handling, JDBC for database interaction, JNDI for
accessing naming and directory services, Enterprise JavaBeans for creating reusable
business components, JMS (Java Messaging Service) for message oriented middleware,
JAXP for XML processing, and JTA (Java Transaction API) for performing atomic
transactions.

• In addition, J2EE also supports servlets, an extremely popular Java substitute for CGI
scripts. The combination of these technologies allows programmers to create
distributed business solutions for a variety of tasks.

• In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java
tools: JavaServer Pages (JSP) which is another Java technology for developing web
applications.

• 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.

What is JSP?
• JavaServer Pages is a technology for developing web pages that include 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.

• A JSP page contains standard markup language elements, such as HTML tags, just like a
regular web page. However, a JSP page also contains special JSP elements that allow the
server to insert dynamic content in the page.

29
H.T

• JSP elements can be used for a variety of purposes, such as retrieving information from
a database or registering user preferences.

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.

Advantages of JSP Technology


• Portability

• Reuse of Components & Tag libraries

• Separation of Static and Dynamic Content

• Suitable for N-Tier Architecture

• Performance

Problem with Servlets


• JSP is based on the servlet technology which was introduced by Sun in 1996 as small
Java-based applications for adding dynamic content to web applications. While servlets
are great in many ways, they are cumbersome to program and thus generally reserved
for programmers.

• However for servlets even a small change in code one needs to call the developer.

30
H.T

• In a servlet each HTML tag must be embedded in a String and sent using the println
method of the PrintWriter object. Combining fixed or static template data with dynamic
content is easier with JSP.

• In any web application, a program on the server processes requests and generates
responses. In a simple one-page application, one need not be concerned about the
design of this piece of code; all logic can be lumped together in a single program.
However for larger web applications this is not desirable. JSP pages offer separation of
business logic from view.

• JSP technology can be used as an important part in all kinds of web applications, from
the simplest to the most complex.

• According to Sun,”JSP technology is an extension of servlet technology created to


support authoring of HTML and XML pages.”

Writing a JSP file


• A JSP page consists of interwoven HTML tags and Java code.

• The HTML tags represent the presentation part and the code produces the contents.

• In its most basic form, a JSP page can include only the HTML part.

• //SimplePage. jsp

• <HTML>

• <HEAD> </HEAD>

• <BODY> JSP is easy. </BODY>

• </HTML>

• To write Java code in your JSP file, you embed the code in <% … %> tags. Ex:

<BODY><% out.println("JSP is easy"); %></BODY>

How JSP Works?

• Inside the JSP container is a special servlet called the page compiler. The servlet
container is configured to forward to this page compiler all HTTP requests with URLs
that match the .jsp file extension.

31
H.T

• This page compiler turns a servlet container into a JSP container. When a .jsp page is
first called, the page compiler parses and compiles the .jsp page into a servlet class.

• If the compilation is successful, the jsp servlet class is loaded into memory. On
subsequent calls, the servlet class for that .jsp page is already in memory; however, it
could have been updated. Therefore, the page compiler servlet will always compare the
timestamp of the jsp servlet with the jsp page. If the .jsp page is more current,
recompilation is necessary.

• With this process, once deployed, JSP pages only go through the time-consuming
compilation process once.

• To save the user from the unpleasant situation of a compiling JSP page , a mechanism in
JSP allows the .jsp pages to be pre-compiled before any user request for them is
received. Alternatively, you can also deploy your JSP application as a web archive file in
the form of a compiled servlet.

JSP Architecture:
• JSP pages are high level extension of servlet and it enable the developers to embed java
code in html pages. JSP files are finally compiled into a servlet by the JSP engine.
Compiled servlet is used by the engine to serve the requests.

• javax.servlet.jsp package defines two interfaces:

• JSPPage

• HttpJspPage

• These interfaces defines the three methods for the compiled JSP page. These methods
are:

• jspInit()

• jspDestroy()

• _jspService(HttpServletRequest request,HttpServletResponse response)

In the compiled JSP file these methods are present. Programmer can define jspInit() and
jspDestroy() methods, but the _jspService(HttpServletRequest
request,HttpServletResponse response) method is generated by the JSP engine.

32
H.T

33
H.T

JSP Lifecycle:

• The key to understanding the low-level functionality of JSP is to understand the simple
life cycle they follow.

• A JSP life cycle can be defined as the entire process from its creation till the destruction
which is similar to a servlet life cycle with an additional step which is required to
compile a JSP into servlet.

• The following are the paths followed by a JSP

• Compilation

• Initialization

• Execution

• Cleanup

• JSP Compilation: When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page. If the page has never been compiled, or if the JSP
has been modified since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps: Parsing the JSP; Turning the JSP into a servlet;
Compiling the servlet.

34
H.T

• JSP Initialization: When a container loads a JSP it invokes the jspInit() method before
servicing any requests.

• public void jspInit(){ // Initialization code... } Initialization is performed only once and as
with the servlet init(), you generally initialize database connections, open files, and
create lookup tables in the jspInit ().

• JSP Execution: This phase represents all interactions with requests until the JSP is
destroyed. Whenever a JSP page is requested, loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.

• void _jspService(HttpServletRequest request, HttpServletResponse response) { //


Service handling code... } The _jspService() method of a JSP is invoked once per a
request and is responsible for generating the response for that request and this method
is also responsible for generating responses to all seven of the HTTP methods ie. GET,
POST, DELETE etc.

• JSP Cleanup:The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.

• public void jspDestroy() { // Your cleanup code goes here. }

The JSP API:


• The JSP technology is based on the JSP API that consists of two packages:
javax.servlet.jsp and javax.servlet.jsp.tagext.

• In addition to these two packages, JSP also needs the two servlet packages—
javax.servlet and javax.servlet.http.

• The javax.servlet.jsp package has two interfaces and four classes. The interfaces are as
follows:

• JspPage

• HttpJspPage

• The four classes are as follows:

• JspEngineInfo

• JspFactory

35
H.T

• JspWriter

• PageContext

In addition, there are also two exception classes: JspException and JspError.

The JspPage Interface:


• The JspPage is the interface that must be implemented by all JSP servlet classes. The
JspPage interface does extend the javax.servlet.Servlet interface.

• The JSPPage interface has two methods, JspInit() and JspDestroy(), whose signatures are
as follows:

• public void jspInit()

• public void jspDestroy()

• jspInit, which is similar to the init method in the javax.servlet.Servlet interface, is called
when the JspPage object is created and can be used to run some initialization. This
method is called only once during the life cycle of the JSP page: the first time the JSP
page is invoked.

• The jspDestroy method is analogous with the destroy method of the


javax.servlet.Servlet interface. This method is called before the JSP servlet object is
destroyed. You can use this method to do some clean-up, if you want.

• Most of the time, however, JSP authors rarely make full use of these two methods.

JSP CLASSES:
The JspFactory Class:

The JspFactory class is an abstract class that provides methods for obtaining other objects
needed for the JSP page processing. The class has the static method getDefaultFactory() that
returns a JspFactory object. From the JspFactory object, a PageContext and a JspEngineInfo
object can be obtained that are useful for the JSP page processing. These objects are obtained
using the JspFactory class's getEngineInfo() method and the getPageContext method().

The JspEngineInfo Class:

• The JspEngineInfo class is an abstract class that provides information on the JSP
container.

36
H.T

• Only one method, getSpecificationVersion(), returns the JSP container's version number.
Because this is the only method currently available, this class does not have much use.

You can obtain a JspEngineInfo object using the getEngineInfo() method of the JspFactory class.

The PageContext Class:

• PageContext represents a class that provides methods that are implementation-


dependent.

• The PageContext class itself is abstract, so in the _ jspService method of a JSP servlet
class, a PageContext object is obtained by calling the getPageContext() method of the
JspFactory class.

The JspWriter Class:

• The JspWriter class is derived from the java.io.Writer class and represents a Writer that
you can use to write to the client browser. Of its many methods, the most important are
the print and println methods. Both provide enough overloads that ensure you can write
any type of data. The difference between print and println is that println always adds
the new line character to the printed data.

JSP Syntax:
• A JSP page can have Java code and HTML tags. More formally, a JSP page has elements
and template data. The elements, also called JSP tags, make up the syntax and
semantics of JSP. Template data is everything else. Template data includes parts that
the JSP container does not understand, such as HTML tags.

• There are three types of elements: Directive elements, Scripting elements , Action
elements.

• Elements have two forms: the XML form and the <% … %> alternative form.

JSP Directives:
• JSP directives provide directions and instructions to the container, telling it how to
handle certain aspects of JSP processing.

• A JSP directive affects the overall structure of the servlet class. It usually has the
following form:

• <%@ directive attribute="value" %>

37
H.T

• Directives can have a number of attributes which you can list down as key-value pairs
and separated by commas.

• The blanks between the @ symbol and the directive name, and between the last
attribute and the closing %>, are optional.

• There are three types of directive tag:

The page Directive:


• The page directive is used to provide instructions to the container that pertain to the
current JSP page. You may code page directives anywhere in your JSP page. By
convention, page directives are coded at the top of the JSP page.

• Following is the basic syntax of page directive:

• <%@ page attribute="value" %>

• Following list of attributes associated with the page directive:

38
H.T

The include Directive:

• The include directive is used to include a file during the translation phase. This directive
tells the container to merge the content of other external files with the current JSP
during the translation phase. You may code include directives anywhere in your JSP
page.

• The general usage form of this directive is as follows:

• <%@ include file="relative url“ %>

The taglib Directive:

• The JavaServer Pages API allows you to define custom JSP tags that look like HTML or
XML tags and a tag library is a set of user-defined tags that implement custom behavior.

• The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides a means for identifying the custom tags in your JSP
page.

• The taglib directive follows the following syntax:

• <%@ taglib uri="uri" prefix="prefixOfTag" >

JSP Scripting Elements:


• JSP scripting elements let you insert code into the servlet that will be generated from
the JSP page. There are three forms:

1. Expressions of the form <%= expression %>, which are evaluated and inserted into the
servlet’s output

2. Scriptlets of the form <% code %>, which are inserted into the servlet’s _jspService method
(called by service)

3. Declarations of the form <%! code %>, which are inserted into the body of the servlet class,
outside of any existing methods.

Scriptlets:

• Scriptlets are the code blocks of a JSP page. Scriptlets start with an opening <% tag and
end with a closing %> tag. Ex:

• <%@ page session="false" %> <%@ page import="java.sql.*" %>

39
H.T

• <% try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("JDBC


driver loaded"); }

• catch (ClassNotFoundException e) { System.out.println(e.toString()); } %> <HTML>


<HEAD> <TITLE>Display All Users</TITLE> </HEAD> <BODY> <CENTER>
<BR><H2>Displaying All Users</H2> <BR> <BR> <TABLE> <TR> <TH>First Name</TH>
<TH>Last Name</TH>

• <TH>User Name</TH> <TH>Password</TH> </TR>

Declarations:

• Declarations allow you to declare methods and variables that can be used from any
point in the JSP page.

• Declarations also provide a way to create initialization and clean-up code by utilizing the
jspInit() and jspDestroy() methods.

• A declaration starts with a <%! and ends with a %> and can appear anywhere
throughout the page. For example, a method declaration can appear above a page
directive that imports a class, even though the class is used in the method.

• <%! String getSystemTime() { return Calendar.getInstance().getTime().toString(); } %>

• <%@ page import="java.util.Calendar" %>

• <%@ page session="false" %>

• <% out.println("Current Time: " + getSystemTime()); %>

• <%! int i; %>

JSP Standard Actions

JSP Standard Action Elements:


• Standard action elements basically are tags that can be embedded into a JSP page. At
compile time, they also are replaced by Java code that corresponds to the predefined
task.

• The JSP standard action elements are:

• jsp:useBean ; jsp:setProperty ; jsp:getProperty ; jsp:param ; jsp:include ; jsp:forward ;


jsp:plugin ; jsp:params ; jsp:fallback

40
H.T

• The jsp:useBean, jsp:setProperty, and jsp:getProperty elements are related to Bean.

• The jsp:param element is used in the jsp:include, jsp:forward, and jsp:plugin elements to
provide information in the name/value format.

jsp:include:

• The jsp:include action element is used to incorporate static or dynamic resources into
the current page. This action element is similar to the include directive, but jsp:include
provides greater flexibility because you can pass information to the included resource.

• The syntax for the jsp:include action element has two forms. For the jsp:include element
that does not have a parameter name/value pair, the syntax is as follows: <jsp:include
page="relativeURL" flush="true"/>

• If you want to pass information to the included resource, use the second syntax:

• <jsp:include page="relativeURL" flush="true"> ( <jsp:param . . . /> )* </jsp:include>

jsp:forward

• The jsp:forward action element is used to terminate the execution of the current JSP
page and switch control to another resource. You can forward control either to a static
resource or a dynamic resource.

• The syntax for the jsp:forward action element has two forms. For the jsp:forward
element that does not have a parameter name/value pair, the syntax is as follows:

<jsp:forward page="relativeURL"/> If you want to pass information to the included


resource.

jsp:plugin

The jsp:plugin action element is used to generate HTML <OBJECT> or <EMBED> tags
containing appropriate construct to instruct the browser to download the Java Plugin
software, if required, and initiates the execution of a Java applet or a JavaBeans
component specified.

jsp:params

The jsp:params action element can occur only as part of the <jsp:plugin> action.

41
H.T

Comments:

• Two types of comments are allowed inside a JSP page:

• Comments that are to be displayed in the resulting HTML page at the client browser

• Comments used in the JSP page itself

• For comments that are meant to be displayed in the HTML page, you use the comments
tags in HTML. This kind of comment must be sent as normal text in a JSP page. For
example, the following code sends an HTML comment to the browser:

• <% out.println("<!–– Here is a comment ––>"); %>

• This is equivalent to the following:

<!–– Here is a comment ––> For comments in the JSP page itself, you use the <%–– … ––
%> tag pair.

Converting into XML syntax:

• JSP pages can also be represented using XML, and representing a JSP page as an XML
document presents the following benefits:

• The content of the JSP page can be validated against a set of descriptions.

• The JSP page can be manipulated using an XML tool.

• The JSP page can be generated from a textual representation by applying an XML
transformation.

JSP Implicit Objects:


• Implicit objects in jsp are the objects that are created by the container automatically
and the container makes them available to the developers, the developer do not need
to create them explicitly.

• Since these objects are created automatically by the container and are accessed using
standard variables; hence, they are called implicit objects.

• The implicit objects are parsed by the container and inserted into the generated servlet
code.

42
H.T

• They are available only within the jspService method and not in any declaration.

• Implicit objects are used for different purposes. Our own methods (user defined
methods) can't access them as they are local to the service method and are created at
the conversion time of a jsp into a servlet.

• But we can pass them to our own method if we wish to use them locally in those
functions.

Implicit Objects:

There are a total of nine implicit objects, which are listed as follows:

• Application: These objects has an application scope. These objects are available at the
widest context level, that allows to share the same information between the JSP page's
servlet and any Web components with in the same application.

• Config: These object has a page scope and is an instance of javax.servlet.ServletConfig


class. Config object allows to pass the initialization data to a JSP page's servlet.
Parameters of this objects can be set in the deployment descriptor (web.xml) inside the
element <jsp-file>. The method getInitParameter() is used to access the initialization
parameters.

• Exception: This object has a page scope and is an instance of java.lang.Throwable class.
This object allows the exception data to be accessed only by designated JSP "error
pages."

43
H.T

• Out: This object allows us to access the servlet's output stream and has a page scope.
Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output
stream that enable access to the servlet's output stream.

• Page: This object has a page scope and is an instance of the JSP page's servlet class that
processes the current request. Page object represents the current page that is used to
call the methods defined by the translated servlet class. First type cast the servlet
before accessing any method of the servlet through the page.

• Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP
page itself that provides a single API to manage the various scoped attributes. This API is
extensively used if we are implementing JSP custom tag handlers. PageContext also
provides access to several page attributes like including some static or dynamic
resource.

• Request: Request object has a request scope that is used to access the HTTP request
data, and also provides a context to associate the request-specific data. Request object
implements javax.servlet.ServletRequest interface. It uses the getParameter() method
to access the request parameter. The container passes this object to the _jspService()
method.

• Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object. Response object is an instance of the classes that
implements the javax.servlet.ServletResponse class. Container generates to this object
and passes to the _jspService() method as a parameter.

• Session: Session object has a session scope that is an instance of


javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to
manage the state contexts. This object persist information across multiple user
connection.

JSP Design Strategies:


• Many dozens of design strategies have been developed for web applications

• We introduce two here :

1. Page-centric : Requests are made to JSPs, and the JSPs respond to clients

2. Dispatcher : Requests are sent to JSPs or servlets that then forward the requests to
another JSP or servlet

44
H.T

• In both cases, the goal is to separate logic from presentation and to separate as many
concerns in the logic as possible

1) Page-Centric Design/ Client-Server Design:

• This is a simple design to implement

• The JSP author can generate pages easily

• Two variants :

– Page-View

– Page-View with a Bean

• Does not scale up very well to large web sites

• Often results in a lot of Java code in the – JSP authors must be Java programmers

– Design is hard to see

– Hard to maintain

Page-View Design:

• A JSP page and some back-end business processing

45
H.T

• Simple but not sophisticated or scalable.

Page-View with Bean Design

• When more business processing and data access is needed

• Let Java Beans handle the data

• Separates programming (Bean) from presentation (JSP)

Dispatcher Design:
• A “dispatcher” accepts requests and routes them to the correct place

• Front-end JSP (or servlet) looks at a portion of the request, and then chooses the
correct place to forward it

• This is more sophisticated than the page-centric :

– More flexible and scalable

46
H.T

– More overhead that is wasted with small applications

• Three versions

– Mediator-View

– Mediator-Composite View

– Service to Workers

Mediator-View Design:
• The Mediating JSP sends requests to a JSP

• The JSP sets and gets beans and creates a response page

Mediator-Composite Design:

• The mediator-view helps with dynamically changing data, but sometimes the structure
around the data changes

• Consider a web site that sells books, CDs, and videos

– The title, author and price form the data

– The structure will be different with each type of item

• With a mediator-view, the JSP has to be changed to introduce new types of products

• The mediator-composite architecture allows nesting of mediator JSPs and HTML …

47
H.T

Service-to-Workers Design:

• The mediator sends requests to “worker beans”

• The worker beans use the back-end software to populate the beans with data

• The JSPs then take the data and create output pages

• This method breaks up the “view” and the “controller”

• Useful when many methods are needed to generate the data

Framework:
• A framework is simply defined as a structure that you can build upon

When you start a new application, a framework allows you to not futz with the under-
workings every application needs. It gives you a head start

48
H.T

Struts:
• Struts is a framework that promotes the use of the Model-View-Controller architecture
for designing large scale applications.

• The framework includes a set of custom tag libaries and their associated Java classes,
along with various utility classes.

• The most powerful aspect of the Struts framework is its support for creating and
processing web-based forms.

• According to the Struts main page: Apache Struts is a free open-source framework for
creating Java web applications.

• According to Wikipedia: Apache Struts is an open-source framework for developing


Java EE web applications. It uses and extends the Java Servlet API to encourage
developers to adopt a model-view-controller (MVC) architecture.

• Struts is a framework that builds upon the framework provided by J2EE and gives you a
starting point to build a web application.

• It allows you to worry less about the mundane mechanics (how requests get handled,
how do requests get routed)

• It makes it a little more difficult to deviate from the MVC pattern

What is the Struts Framework?

• The Struts Framework is a standard for developing well-architected Web applications. It


has the following features:

• Open source

• Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all


three levels:

– Model: application state

– View: presentation of data (JSP, HTML)

– Controller: routing of the application flow

49
H.T

Struts Architecture:

• All incoming requests are intercepted by the Struts servlet controller. The Struts
Configuration file struts-config.xml is used by the controller to determine the routing of
the flow. This flows consists of an alternation between two transitions:

Components of Struts:
Struts consist of four main components:

1. The Struts Framework: Java classes that provide the ActionServlet and Action classes as
part of the MVC Controller, the ActionForm class to facilitate moving data to and from
the View, and the ActionForward class to aid the controller in forwarding requests.

50
H.T

2. JSP Tag Libraries: Tags expand on HTML forms and fields, help you work with beans and
provide other useful features.

3. Tiles Plugin: Allows you to create HTML in re-usable pieces (tiles) that can be put together to
make a whole page

4. Validator Plugin: Allows you specify validation information in an xml file and then perform
those validations in the browser and/or the on the server.

• The Controller

• This receives all incoming requests. Its primary function is the mapping of a request URI
to an action class selecting the proper application module. It's provided by the
framework.

• The struts-config.xml File

• This file contains all of the routing and configuration information for the Struts
application. This XML file needs to be in the WEB-INF directory of the application.

• Action Classes

• It's the developer's responsibility to create these classes. They act as bridges between
user-invoked URIs and business services. Actions process a request and return an
ActionForward object that identifies the next component to invoke. They're part of the
Controller layer, not the Model layer.

• View Resources

• View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files,
Resource bundles, JavaBeans, and Struts JSP tags.

• ActionForms

• These greatly simplify user form validation by capturing user data from the HTTP
request. They act as a "firewall" between forms (Web pages) and the application
(actions). These components allow the validation of user input before proceeding to an
Action. If the input is invalid, a page with an error can be displayed.

• Model Components

• The Struts Framework has no built-in support for the Model layer. Struts supports any
model components:

51
H.T

• JavaBeans; EJB

• CORBA; JDO

Struts Advantages:

• Struts has fundamentally reshaped the way that Web programmers think about and
structure a Web application. It is a technology that no Web programmer can afford to
ignore.

• Struts reduce the development maintainence time of enterprise web applications.

Struts is open-source

 Form beans
 Bean tags
 HTML tags
 Form field validation
 Consistent approach

Struts Disadvantages:

• Bigger learning curve

• Worse documentation

• Less transparent

• Rigid approach

Struts Applications:

• Travelocity

52
H.T

rd
UNIT 3
EJB Fundamentals:

What is an Enterprise Java Bean?


• In a nutshell, an enterprise JavaBean is a Java-based server-side component. Just like
any other component, an enterprise bean encapsulates business logic of an application.

• Enterprise beans must conform to the EJB specifications, however, and they are
deployed and can run only in an EJB container, identical to the way servlets run inside a
servlet container.

• A servlet container provides services for servlets, such as session management and
security.

• Likewise, an EJB container provides system-level services for EJB applications. In fact, as
you will soon find out, it's the EJB container that makes EJB so great.

• Despite the similarity of names, EJB has little to do with JavaBeans.

Benefits of EJB:

• EJB applications are much more complex and more difficult to build and administer than
servlets/JSP applications.

• For someone new to EJB, the learning curve also is steeper. If this is the case, why is EJB
so popular and why do so many organizations want to invest in it? The answer is
simple—after you know the nuts and bolts of EJB, writing an application is an easy task,
and, more importantly, you can enjoy some benefits provided for you by the EJB
container.

• The following is the list of some of the benefits of EJB:

-EJB applications are easy to develop because the application developer can concentrate
on the business logic. At the same time, the developer uses the services provided by the
EJB container, such as transactions and connection pooling. Again, the hardest part is
the learning process.

53
H.T

When to use EJB?

• An enterprise java bean can be used if an application has any of the following
requirement:

a) The application must be scalable. To accommodate a growing number of users, one may
need to distribute an application’s components across multiple machines, but their
location will remain transparent to the clients.

b) Transactions are required to ensure data integrity. Enterprise beans support


transactions, the mechanisms that manage the concurrent access of shared objects.

c) The application will have a variety of clients. With just a few lines of code, remote
clients can easily locate enterprise beans. These clients can be thin, various and
numerous.

EJB Application Architecture

• The Enterprise JavaBeans (EJB) technology defines a model for the development and
deployment of reusable Java server components, called EJB components. An EJB
component is a non-visual server component with methods that typically provide
business logic in distributed applications.

• A remote client, called an EJB client, can invoke these methods, which typically results
in database updates.

54
H.T

• EJB server The EJB server contains the EJB container, which provides the services
required by the EJB component. EAServer is an EJB server.

EJB client An EJB client usually provides the user-interface logic on a client machine. The EJB
client makes calls to remote EJB components on a server and needs to know how to find the
EJB server and how to interact with the EJB components. An EJB component can act as an EJB
client by calling methods in another EJB component

• An EJB client does not communicate directly with an EJB component. The container
provides proxy objects that implement the components home and remote interfaces.
The component’s remote interface defines the business methods that can be called by
the client. The client calls the home interface methods to create and destroy proxies for
the remote interface.

• EJB container The EJB specification defines a container as the environment in which one
or more EJB components execute. The container provides the infrastructure required to
run distributed components, allowing client and component developers to focus on
programming business logic, and not system-level code.

EJB component implementation The Java class that runs in the server implements the bean’s
business logic. The class must implement the remote interface methods and additional
methods for lifecycle management.

Motivation for EJB:

• EJB Advantages

1. The underpinning EJB specification

2. Integration with the J2EE platform

3. Almost transparent scalability

4. Free access and usage of complex resources

5. A strong and vibrant industry and community

• EJB Disadvantages

1. Large, complicated specification

2. Increased development time

55
H.T

3. Added complexity compared to straight Java classes

4. Potential to produce a more complex and costly solution than is necessary

Continual specification revisions

EJB Echo System:


• To have an EJB deployment up and running, one needs more than an application server
and components. There are six more parties involved:

1. The Bean provider: The bean provider supplies the business components to the
enterprise applications. These business components are not complete applications but
can be combined to form complete enterprise applications. These bean providers could
be an external provider selling components or an internal component provider.

2. The Application Assembler: The application assembler is responsible for integrating the
components. This party writes applications to combine components so as to develop the
target application that can be deployed under various environments.

3. The EJB Deployer: After the application developer builds the application, the application
must be deployed on the server. This involves configuring the security parameter
settings, performance tuning, etc. An application assembler is not familiar with these
issues. This is where the EJB deployer comes into play.

4. The System Administrator: The system administrator is responsible for the upkeep and
monitoring of the deployed system and may make use of monitoring and management
tools to closely observe the deployed system.

5. The Container and Server providers: The container provider supplies the EJB container
(an application server). This is the runtime environment where the beans live. The
container supplies the middleware services to the beans and manages them. Some of
the various containers are: BEA's WebLogic, iPlanet's iPlanet Application Server, IBM's
WebSphere, Oracle's Oracle 9i Application Server and Oracle 10g Application Server, and
the JBoss open source Application Server. The server provider is the same as the
container provider.

6. The Tool Vendors: There are various IDEs available to assist the developer in rapidly
building and debugging components, for example Eclipse, NetBeans, and JBuilder. For

56
H.T

the modeling of components one can use Rational Rose. There are many other tools,
some used for testing (JUnit) and others used for building (Ant, XDoclet).

Java Beans versus Enterprise Java Beans:

• JavaBeans are completely different from Enterprise JavaBeans.

• In a nutshell, JavaBeans are Java classes that have get/set methods on them. They are
reusable Java components with properties, events, and methods (similar to Microsoft
ActiveX controls) that can be easily wired together to create (often visual) Java
applications.

• The JavaBeans framework is lightweight compared to Enterprise JavaBeans. You can use
JavaBeans to assemble larger components or to build entire applications.

• JavaBeans, however, are development components and are not deployable


components. You typically do not deploy a JavaBean; rather, JavaBeans help you
construct larger software that is deployable. And because they cannot be deployed,
JavaBeans do not need to live in a runtime environment and hence, in a container.

J2EE Technologies:
• EJB is only a portion of a larger offering from the Java Community Process (a.k.a. JCP—a
Java industry standards body) called the Java 2 Platform, Enterprise Edition (J2EE).

• The mission of J2EE is to provide a platform-independent, portable, multiuser, secure,


and standard enterprise-class platform for server-side deployments written in the Java
language.

• J2EE is a specification, not a product. J2EE specifies the rules of engagement that people
must agree on when writing enterprise software. Vendors then implement the J2EE
specifications with their J2EE-compliant products.

• Because J2EE is a specification (meant to address the needs of many companies), it is


inherently not tied to one vendor; it also supports cross-platform development. This
encourages vendors to compete, yielding best-of-breed products.

57
H.T

The J2EE Technologies:

The various J2EE technologies are as under:


Enterprise JavaBeans (EJB). EJB defines how server-side components are written and
provides a standard contract between components and the application servers that
manage them. EJB is the cornerstone for J2EE and uses several other J2EE technologies.

Java API for XML RPC (JAX-RPC). JAX-RPC is the main technology that provides support
for developing Web Services on the J2EE platform. It defines two Web Service endpoint
models—one based on servlet technology and another based on EJB. It also specifies a
lot of runtime requirements regarding the way Web Services should be supported in a
J2EE runtime.

Java Remote Method Invocation (RMI) and RMI-IIOP. RMI is the Java language’s native
way to communicate between distributed objects, such as two different objects running
on different machines.

Java Naming and Directory Interface (JNDI). JNDI is used to access naming and
directory systems. You use JNDI from your application code for a variety of purposes,
such as connecting to EJB components or other resources across the network, or
accessing user data stored in a naming service such as Microsoft Exchange or Lotus
Notes.

Java Database Connectivity (JDBC). JDBC is an API for accessing relational databases.
The value of JDBC is that you can access any relational database using the same API.

Java Transaction API (JTA) and Java Transaction Service (JTS). The JTA and JTS
specifications allow for components to be bolstered with reliable transaction support.

Java Messaging Service (JMS). JMS allows for your J2EE deployment to communicate
using messaging. You can use messaging to communicate within your J2EE system as
well as outside your J2EE system.

Java servlets. Servlets are networked components that you can use to extend the
functionality of a Web server. Servlets are request/response oriented in that they take
requests from some client host (such as a Web browser) and issue a response back to
that host.

Java IDL. Java IDL is the Sun Microsystems Java-based implementation of CORBA. Java
IDL allows for integration with other languages.

58
H.T

Enterprise Bean and its Types:


• An enterprise bean is a server-side software component that can be deployed in a
distributed multitier environment. An enterprise bean can compose one or more Java
objects because a component may be more than just a simple object.

Regardless of an enterprise bean’s composition, the clients of the bean deal with a single
exposed component interface. This interface, as well as the enterprise bean itself, must
conform to the EJB specification. The specification requires that your beans expose a few
required methods; these required methods allow the EJB container to manage beans uniformly,
regardless of which container your bean is running in.

Types of Beans:

• EJB 2.1 defines three different kinds of enterprise beans:

i) Session beans. Session beans model business processes. They are like verbs because
they perform actions. The action could be anything, such as adding numbers, accessing a
database, calling a legacy system, or calling other enterprise beans. Examples include a
pricing engine, a workflow engine, a catalog engine, a credit card authorizer, or a
stocktrading engine.

• Entity beans. Entity beans model business data. They are like nouns because they are
data objects—that is, Java objects that cache database information. Examples include a
product, an order, an employee, a credit card, or a stock. Session beans typically harness
entity beans to achieve business goals, such as a stock-trading engine (session bean)
that deals with stocks (entity beans).

Message-driven beans. Message-driven beans are similar to session beans in that they perform
actions. The difference is that you can call message-driven beans only implicitly by sending
messages to those beans.

Distributed Objects and Middleware

Distributed Objects: The Foundation for EJB:

• EJB components are based on distributed objects.


A distributed object is an object that is callable from a remote system. It can be called from an
in-process client, an out-of-process client, or a client located elsewhere on the network

59
H.T

Distributed Objects and Middleware:

• Distributed objects are great because they enable you to break up an application across
a network. However, as a distributed object application gets larger, you’ll need help
from middleware services, such as transactions and security.

• There are two ways to get middleware: explicitly and implicitly.

Explicit Middleware:

• In traditional distributed object programming (such as traditional CORBA), you can


harness middleware by purchasing that middleware off the shelf and writing code that
calls that middleware’s API.

• For example, you could gain transactions by writing to a transaction API. We call this
explicit middleware because you need to write to an API to use that middleware.

• This approach is:

60
H.T

i) Difficult to write. The code is bloated. We simply want to perform a transfer, but it
requires a large amount of code.

ii) Difficult to maintain. If you want to change the way you do middleware, you need to
rewrite your code.

iii) Difficult to support. If you are an Independent Software Vendor (ISV) selling an
application, or an internal department providing code to another department, you are
unlikely to provide source code to your customers.

Implicit Middleware:

• The crucial difference between systems of the past (transaction processing monitors
such as TUXEDO or CICS, or traditional distributed object technologies such as CORBA,
DCOM, or RMI) and the newer, component-based technologies (EJB, CORBA Component
Model, and Microsoft.NET) is that in this new world, you can harness complex
middleware in your enterprise applications without writing to middleware APIs.

Declare the middleware services that your distributed object needs in a separate
descriptor file, such as a plain text file. For example, you might declare that you need
transactions, persistence, and a security check.

61
H.T

3. Run a command-line tool provided for you by the middleware vendor. This tool takes
your descriptor file as input and generates an object that we’ll call the request
interceptor.

4. The request interceptor intercepts requests from the client, performs the middleware
that your distributed object needs (such as transactions, security, and persistence), and
then delegates the call to the distributed object.

• The values of implicit middleware (also called declarative middleware) are:

i) Easy to write.

ii) Easy to maintain.

iii) Easy to support

Developing EJB Components:


• When building an EJB component, the following is a typical order of operations:

1. Write the .java files that compose your bean: the component interfaces, home
interfaces, enterprise bean class file, and any helper classes you might need.

62
H.T

2. Write the deployment descriptor, or have it generated by your IDE or tools like XDoclet.

3. Compile the .java files from Step 1 into .class files.

4. Using the jar utility, create an Ejb-jar file containing the deployment descriptor and .class
files.

5. Deploy the Ejb-jar file into your container in a vendor-specific manner, perhaps by running a
vendor-specific tool or perhaps by copying your Ejb-jar file into a folder where your container
looks to load Ejb-jar files.

Configure your EJB server so that it is properly configured to host your Ejb-jar file. You might
tune things such as database connections, thread pools, and so on. This step is vendor-specific
and might be done through a Web-based console or by editing a configuration file.

7. Start your EJB container and confirm that it has loaded your Ejb-jar file.

8. Optionally, write a standalone test client .java file and let vendor tools generate stub classes
for remote access, if required. Compile that test client into a .class file. Run the test client from
the command line and have it exercise your bean’s APIs

Remote, Local and Home Interface:


The Remote Interface:
• The remote interface supports every business method that our beans expose. Things to
notice about our remote interface include the following:

• We extend javax.ejb.EJBObject. This means that the container-generated EJB object,


which implements the remote interface, will contain every method that the
javax.ejb.EJBObject interface defines. This includes a method to compare two EJB
objects, a method to remove an EJB object, and so on.

• We have one business method—hello()—which returns the String “Hello, World!” to the
client. We need to implement this method in our enterprise bean class. Because the
remote interface is an RMI-IIOP remote interface (it extends java.rmi.Remote), it must
throw a remote exception. This is the only difference between the remote interface’s
hello() signature and our bean’s hello() signature. The exception indicates a networking
or other critical problem.

63
H.T

//Hello.java

• package examples;

• /**

• * This is the HelloBean remote interface.

• *

• * This interface is what clients operate on when they interact with EJB *objects. The
container vendor will implement this interface; the *implemented object is the EJB
object, which delegates invocations to the

* actual bean.

• */

• public interface Hello extends javax.ejb.EJBObject{

• /**

• * The one method - hello - returns a greeting to the client.

• */

• public String hello() throws java.rmi.RemoteException;

• }

The Local Interface:


• Local clients will use local interface, rather than the remote interface, to call our beans’
methods. (//HelloLocal.java)

• package examples;

• /**

• * This is the HelloBean local interface.This interface is what local clients *operate on
when they interact with EJB local objects. The container vendor *will implement this
interface; the implemented object is the EJB local *object, which delegates invocations
to the actual bean.

64
H.T

• */

• public interface HelloLocal extends javax.ejb.EJBLocalObject

• {

• /**

• * The one method - hello - returns a greeting to the client.

• */

• public String hello();

• }

The Home Interface:


• The home interface has methods to create and destroy EJB objects. The implementation
of the home interface is the home object, which is generated by the container tools.

• /**

• * This is the home interface for HelloBean. This interface is implemented *by the EJB
Server’s tools – the implemented object is called the Home *Object, and serves as a
factory for EJB Objects.One create() method is in *this Home Interface, which
corresponds to the ejbCreate() method in *HelloBean.

• */

• public interface HelloHome extends javax.ejb.EJBHome{

• /*

* This method creates the EJB Object.@return The newly created EJB Object.

• */

• Hello create() throws java.rmi.RemoteException,

• javax.ejb.CreateException; }

65
H.T

The Local Home Interface:


• Is the higher-performing home interface used by local clients.

• package examples;

• /**

• * This is the local home interface for HelloBean. This interface is *implemented by the
EJB Server’s tools - the implemented object is *called the local home object, and serves
as a factory for EJB local *objects.

• */

• public interface HelloLocalHome extends javax.ejb.EJBLocalHome

• {

• /*

• * This method creates the EJB Object.

• * @return The newly created EJB Object.

• */

• HelloLocal create() throws javax.ejb.CreateException;

• }

Bean Class:
package examples;

/** Demonstration stateless session bean.*/

public class HelloBean implements javax.ejb.SessionBean {

private SessionContext ctx;

// EJB-required methods

public void ejbCreate() {System.out.println(“ejbCreate()”);}

public void ejbRemove() {System.out.println(“ejbRemove()”);}


66
H.T

public void ejbActivate() {System.out.println(“ejbActivate()”);}

• This is just about the most basic bean class possible. Notice:

• Our bean implements the javax.ejb.SessionBean interface, which makes it a session


bean. This interface defines a few required methods that you must fill in.

• The container uses these management methods to interact with the bean, calling them
periodically to alert the bean to important events. For example, the container will alert
the bean when it is being initialized and when it is being destroyed. These callbacks are
not intended for client use, so you will never call them directly—only your EJB container
will. The bean has an ejbCreate() method that matches the home object’s create()
method, and takes no parameters.

• We have one business method, hello(). It returns Hello, World! to the client.

The Deployment Descriptor:

• Next, we need to generate a deployment descriptor, which describes our bean’s


middleware requirements to the container. Deployment descriptors are one of the key
features of EJB because they enable you to declaratively specify attributes on your
beans, rather than program this functionality into the bean itself.

• Physically, a deployment descriptor is an XML document. Your EJB container, IDE


environment, or other tool (such as a UML editor that can generate EJB code) should
supply tools to help you generate such a deployment descriptor.

Many different settings make up a deployment descriptor

67
H.T

Enterprise Computing in Java


th
UNIT 4
Introducing session beans:

Session Bean:
• A session bean represents work being performed for client code that is calling it.

• Session beans are business process objects that implement business logic, business
rules, algorithms, and workflow.

• For example, a session bean can perform price quoting, order entry, video compression,
banking transactions, stock trades, database operations, complex calculations, and
more.

• They are reusable components that contain logic for business processes.

Session Bean Lifetime:


• of their lives.

• A session bean instance is a relatively short-lived object. It has roughly the lifetime
equivalent of a session or of the client code that is calling the session bean.

• Session bean instances are not shared between multiple clients.

• For example, if the client code contacted a session bean to perform order entry logic,
the EJB container is responsible for creating an instance of that session bean
component.

• When the client later disconnects, the application server may destroy the session bean
instance.

• A client’s session duration could be as long as a browser window is open, perhaps


connecting to an e-commerce site with deployed session beans.

68
H.T

• It could also be as long as your Java applet is running, as long as a standalone application
is open, or as long as another bean is using your bean.

• The length of the client’s session generally determines how long a session bean is in
use—that is where the term session bean originated.

• The EJB container is empowered to destroy session beans if clients time out. If your
client code is using your beans for 10 minutes, your session beans might live for minutes
or hours, but probably not weeks, months, or years.

• Typically session beans do not survive application server crashes, nor do they survive
machine crashes.

• They are in-memory objects that live and die with their surrounding environments.

Statefull and Stateless Session Beans:


The two subtypes of session beans are stateful session beans and stateless session
beans. Each is used to model different types of these conversations.

Stateful Session Beans:


• A stateful session bean is a bean that is designed to service business processes that span
multiple method requests or transactions. To accomplish this, stateful session beans
retain state on behalf of an individual client. If a stateful session bean’s state is changed
during a method invocation, that same state will be available to that same client upon
the following invocation.

Stateless Session Beans:


• A stateless session bean is a bean that holds conversations that span a single method
call. They are stateless because they do not hold multimethod conversations with their
clients. After each method call, the container may choose to destroy a stateless session
bean, or recreate it, clearing itself out of all information pertaining to past invocations. It
also may choose to keep your instance around, perhaps reusing it for all clients who
want to use the same session bean class. The exact algorithm is container specific.

• The takeaway point is this: Expect your bean to forget everything after each method
call, and thus retain no conversational state from method to method. If your bean
happens to hang around longer, then great—but that’s your container’s decision, and
you shouldn’t rely on it.

69
H.T

• For a stateless session bean to be useful to a client, the client must pass all

• client data that the bean needs as parameters to business logic methods. Alternatively,
the bean can retrieve the data it needs from an external source, such as a database.

• Stateless really means no conversational state. Stateless session beans can contain state
that is not specific to any one client, such as a database connection factory that all
clients would use. You can keep this around in a private variable

• An example of a stateless session bean is a high-performance engine that solves


complex mathematical operations on a given input, such as compression of audio or
video data. The client could pass in a buffer of uncompressed data, as well as a
compression factor. The bean returns a compressed buffer and is then available to
service a different client. The business process spanned one method request. The bean
does not retain any state from previous requests.

Session Bean Life Cycle


A key difference between session beans and other bean types is the scope of their lives.
A session bean instance is a relatively short-lived object. It has roughly the lifetime
equivalent of a session or of the client code that is calling the session bean. Session bean
instances are not shared between multiple clients.

Life Cycle Diagram for Stateless Session Bean:

70
H.T

• A stateless session bean has its life cycle inside the container.

• The client does not call the methods on the bean, since the client never accesses a bean
directly. (The client always goes through the container.) The container (that is, the home
object and EJB objects) calls methods on our bean.

1. At first, the bean instance does not exist. Perhaps the application server has just
started up.

2. The container decides it wants to instantiate a new bean. When does the container
decide it wants to instantiate a new bean? It depends on the container’s policy for
pooling beans.
3. The container instantiates your bean. The container calls Class.newInstance(“
HelloBean.class”) on your session bean class, which is the dynamic equivalent of calling
new HelloBean().
4. . The container calls setSessionContext(). This associates you with a context object,
which enables you to make callbacks to the container
5. The container calls ejbCreate(). This initializes your bean. Note that because stateless
session beans’ ejbCreate() methods take no parameters, clients never supply any critical
information that bean instances need to start up. EJB containers can exploit this and
pre-create instances of your stateless session beans.
6. The container can call business methods on your bean. The container can call as many
business methods as it wants to call. Each business method could originate from a
completely different client because all bean instances are treated exactly the same.
7. Finally, the container calls ejbRemove(). When the container is about to remove your
session bean instance, it calls your bean’s ejbRemove() callback method. ejbRemove() is
a clean-up method, alerting your bean that it is about to be destroyed and allowing it to
end its life gracefully.

71
H.T

• The life cycle for stateful session beans is similar to that of stateless
session beans. The big differences are as follows:

• There is no pool of equivalent instances because each instance contains


state.

• There are transitions for passivating and activating conversational state.

Introducing Entity beans:


• One of the key benefits of EJB is that it gives you the power to create entity beans.
Entity beans are persistent objects that you place in permanent storage.

• This means you can model your business’s fundamental, underlying data as entity
beans.

• A popular way to store Java objects is to use a traditional relational database, such as
Oracle, Microsoft SQL Server, or MySQL. Rather than serialize each object, we could
decompose each object into its constituent parts and store each part separately.

• For example, for a bank account object, the bank account number could be stored in
one relational database field and the bank account balance in another field. When you
save your Java objects, you would use JDBC to map the object data into a relational
database. When you want to

72
H.T

• load your objects from the database, you would instantiate an object from that class,
read the data in from the database, and then populate that object instance’s fields with
the relational data read in.

What is an Entity Bean?

• Entity beans are these persistent data components. Entity beans are enterprise beans
that know how to persist themselves permanently to a durable storage, such as a
database or legacy system.

• They are physical, storable parts of an enterprise. Entity beans store data as fields, such
as bank account numbers and bank account balances. They also have methods
associated with them, such as getBankAccountNumber().

• In some ways, entity beans are analogous to serializable Java objects. Serializable
objects can be rendered into a bit-blob and then saved into a persistent store; entity
beans can persist themselves in many ways, including Java serialization, O/R mapping,
or even an object database persistence. Nothing in the EJB 2.x specification dictates any
particular persistence mechanism, although O/R mappings are the most frequently
used.

Entity beans are different from session beans. Session beans model a process or workflow
(actions that are started by the user and that go away when the user goes away). Entity beans,
on the other hand, contain core business data—product information, bank accounts, orders,
lead tracking information, customer information and more.

Features of Entity Beans:

Entity Beans Survive Failures

• Entity beans are long lasting. They survive critical failures, such as application servers
crashing, or even databases crashing. This is because entity beans are just
representations of data in a permanent, fault-tolerant, underlying storage.

Entity Bean Instances Are a View into a Database

When you load entity bean data into an in-memory entity bean instance, you read in the data
stored in a database so that you can manipulate the data within a Java Virtual Machine.
However, you should think of the in-memory object and the database itself as one and the
same. This means if you update the in-memory entity bean instance, the database should
automatically be updated as well. You should not think of the entity bean as a separate version
of the data in the database

73
H.T

Several Entity Bean Instances May Represent the Same Underlying Data

• If many threads of execution want to access the same database data simultaneously. Ex:
In e-commerce, many different client browsers may be simultaneously interacting with
a catalog of products.

Entity Bean Instances Can Be Pooled

• As clients connect and disconnect, you could create and destroy beans as necessary to
service those clients. Unfortunately this is not a scalable way to build an application
server.

• Creation and destruction of objects is expensive, especially if client requests come


frequently. How can we save on this overhead?

Entity Beans Can Be Found

• Because entity bean data is uniquely identified in an underlying storage, entity beans
can also be found rather than created.

• Finding an entity bean is analogous to performing a SELECT statement in SQL. With a


SELECT statement, you’re searching for data from a relational database store.

You Can Modify Entity Bean Data without Using EJB

• Usually you will create, destroy, and find entity bean data by using the entity bean’s
home object. But you can interact with entity beans another way, too: by directly
modifying the underlying database where the bean data is stored.

Entity Context
• All enterprise beans have a context object that identifies the environment of the bean.

• These context objects contain environment information that the EJB container sets.
Your beans can access the context to retrieve all sorts of information, such as
transaction and security information.

• For entity beans, the interface is javax.ejb.EntityContext.

• Entity contexts add the following methods on top of the generic EJB context.

• public interface javax.ejb.EntityContext extends javax.ejb.EJBContext {

74
H.T

public javax.ejb.EJBLocalObject getEJBLocalObject();

public javax.ejb.EJBObject getEJBObject();

public java.lang.Object getPrimaryKey();

Introduction to JMS & Message driven beans

Message-Driven Beans:
• Messaging is an alternative to remote method invocations.

• The idea behind messaging is that a middleman sits between the client and the server. (A
layer of indirection solves every problem in computer science.) This middleman receives
messages from one or more message producers and broadcasts those messages to one
or more message consumers.

Because of this middleman, the producer can send a message and then continue processing. He
can optionally be notified of the response later when the consumer finishes. This is called
asynchronous programming

• Messaging addresses the three previous concerns with RMI-IIOP as follows:

Non-blocking request processing. A messaging client does not need to block when
executing a request. As an example, when you purchase a book using the Amazon.com
one-click order functionality, you can continue browsing the site without waiting to see
if your credit card authorizes.

Reliability. If your message-oriented middleware supports guaranteed delivery, you


can send a message and know for sure that it will reach its destination, even if the
consumer is not available.

75
H.T

Support for multiple senders and receivers. Most message-oriented middleware


products can accept messages from many senders and broadcast them to many
receivers. This enables you to have multinary communications.

Java Message Service (JMS):


• Over the years, MOM systems have evolved in a proprietary way. Each product
has its own API, which creates vendor lock-in because code is not portable to
other messaging systems. It also hurts developers, because they need to relearn
each messaging product’s proprietary API.

• The Java Message Service (JMS) is a messaging standard, designed to eliminate


many of the disadvantages that MOM-based products faced over past years. JMS
has two parts: an API, for which you write code to send and receive messages,
and a Service Provider Interface (SPI) where you plug in JMS providers. AJMS
provider knows how to talk to a specific MOM implementation.

• The JMS promise is that you can learn the JMS API once and reuse your
messaging code with different plug-and-play MOM implementations (an idea
similar to the other J2EE APIs, such as JNDI or JDBC).

The JMS API:


• The JMS API is more involved than RMI-IIOP. You need to become familiar with
many different interfaces to get going. Despite the complexities involved in
working with each of these interfaces, low-level topology issues, such as
networking protocol, message format and structure, and server location, are
mostly abstracted from the developer.

• The JMS programming model is explained as follows:

1. Locate the JMS Provider ConnectionFactory instance. You first need to get
access to the JMS provider of the particular MOM product you’re using. For this,
you need to establish a connection using a ConnectionFactory instance. You can
get hold of ConnectionFactory by looking it up in JNDI. An administrator will
typically create and configure the ConnectionFactory for the JMS client’s use.

2. Create a JMS connection. A JMS Connection is an active connection to the JMS


provider, managing the low-level network communications (similar to a JDBC

76
H.T

connection). You use the ConnectionFactory to get a Connection. If you’re in a


large deployment, this connection might be load-balanced across a group of
machines.
3. 3. Create a JMS session. A JMS Session is a helper object that you use when
sending and receiving messages. It serves as a factory for message consumers
and producers, and also enables you to encapsulate your messages in
transactions. You use the Connection to get a Session.
4. 4. Locate the JMS destination. A JMS Destination is the channel to which you’re
sending or from which you’re receiving messages. Locating the right destination
is analogous to tuning into the right channel when watching television or
answering the correct phone, so that you get the messages you desire.
5. . Create a JMS producer or a JMS consumer. If you want to send messages, you
need to call a JMS object to pass it your messages. This object is called producer.
To receive messages, you call a JMS object and ask it for a message. This object is
called the Consumer object. You use the Session and Destination to get a hold of a
Producer or a Consumer object.
6. Send or receive your message. If you’re producing, you first need to put your
message together. There are many different types of messages, such as text,
bytes, streams, objects, and maps.

What Is a Message-Driven Bean?


• A message-driven bean, introduced in EJB 2.0, is a special EJB component that can
receive JMS messages as well as other types of messages.
• A message-driven bean is invoked by the container upon arrival of a message at
the destination or endpoint that is serviced by message-driven bean. A message-
driven bean is decoupled from any clients that send messages to it.
• A client cannot access a message-driven bean through a component interface.
You will have to use message provider–specific API, such as JMS, to send
messages from clients, which in turn would be received by the message-driven
beans

77
H.T

Client calling JMS Message-Driven Bean:

Characteristics of Message-Driven Beans

 A message-driven bean does not have a home interface, local home interface, remote
interface, or a local interface. You do not call message- driven beans using an object-
oriented remote method invocation interface.
 Message-driven beans have weakly typed business method. Message driven beans are
merely receiving messages from a destination or a resource adapter and they do not
know anything about what’s inside the messages. The listener interface implemented by
message-driven beans typically has a method (or methods) called by an EJB container
upon arrival of a message or by the resource adapter (via application server).
 Message-driven bean listener method(s) might not have any return values. Although
EJB 2.1 specification does not restrict a message driven bean listener method from
returning a value to the client, certain messaging types might not be suitable for this.
For example, consider the listener interface of a messaging type that supports
asynchronous messaging, such as JMS.
 Message-driven beans might not send exceptions back to clients. Although, EJB 2.1
does not restrict message-driven bean listener interface methods from throwing

78
H.T

application exceptions, certain messaging types might not be able to throw these
exceptions to the clients.

79

You might also like