Unit 1: Enterprise Computing in Java
Unit 1: Enterprise Computing in Java
INTRODUCTION:
• 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
http://java.sun.com/j2se
1
H.T
http://java.sun.com/j2me
http://java.sun.com/j2ee
• J2EE defines a model for developing multi-tier, web based, enterprise applications with
distributed components.
J2EE Provides:
• Enabling technology
– Security
– Session Management
Scalability
2
H.T
• High availability
• Scalability
• 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
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
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.
• 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 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.
• 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
9
H.T
• 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)
or Model state.
the Model.
10
H.T
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
• 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.
– Initializes the servlet instance by calling the init method. Initialization is covered
in Initializing a Servlet.
• If the container needs to remove the servlet, it finalizes the servlet by calling the
servlet's destroy method.
• 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.
• init
• Service
13
H.T
• destroy
– Single copy of code brought into memory for all threads versus per thread
– Data (session state) can be stored across threads within servlet container
– Requires little expense once servlet container integrated with web server
– Loads/unloads servlets
• Request → doGet()
14
H.T
3. HttpServletRequest
– getParameter("paramName")
4. HttpServletResponse
– get PrintWriter
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.
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.
• 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.
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.
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.
• CGI programs are cost effective. By using them businesses can lower their development
and maintenance costs.
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.
• 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.
• 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.
• 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.
• 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
• 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.
• 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.
HttpServlet
19
H.T
• A subclass of HttpServlet must override atleast one method, usually one of these:
init() and destroy() to manage resources that are held for the life of the servlet.
• 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.
• 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:
• 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:
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.
• 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.
• 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
• OR
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.
• 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":
• 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:
• 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 Collaboration:
• Sometimes servlets have to cooperate, usually by sharing some information.
• 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.
• 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:
28
H.T
• 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.
• Performance
• 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.
• 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>
• </HTML>
• To write Java code in your JSP file, you embed the code in <% … %> tags. Ex:
• 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.
• JSPPage
• HttpJspPage
• These interfaces defines the three methods for the compiled JSP page. These methods
are:
• jspInit()
• jspDestroy()
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.
• 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.
• 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.
• 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
• JspEngineInfo
• JspFactory
35
H.T
• JspWriter
• PageContext
In addition, there are also two exception classes: JspException and JspError.
• The JSPPage interface has two methods, JspInit() and JspDestroy(), whose signatures are
as follows:
• 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.
• 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 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 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 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:
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.
38
H.T
• 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 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.
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:
39
H.T
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.
40
H.T
• 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: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: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:
• Comments that are to be displayed in the resulting HTML page at the client browser
• 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:
<!–– Here is a comment ––> For comments in the JSP page itself, you use the <%–– … ––
%> tag pair.
• 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 generated from a textual representation by applying an XML
transformation.
• 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.
• 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.
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
• Two variants :
– Page-View
• Often results in a lot of Java code in the – JSP authors must be Java programmers
– Hard to maintain
Page-View Design:
45
H.T
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
46
H.T
• 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
• With a mediator-view, the JSP has to be changed to introduce new types of products
47
H.T
Service-to-Workers Design:
• The worker beans use the back-end software to populate the beans with data
• The JSPs then take the data and create output pages
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.
• 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)
• Open source
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.
• 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 is open-source
Form beans
Bean tags
HTML tags
Form field validation
Consistent approach
Struts Disadvantages:
• Worse documentation
• Less transparent
• Rigid approach
Struts Applications:
• Travelocity
52
H.T
rd
UNIT 3
EJB Fundamentals:
• 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.
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.
-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
• 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.
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.
• 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.
• EJB Advantages
• EJB Disadvantages
55
H.T
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).
• 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.
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).
• 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.
57
H.T
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
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:
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.
59
H.T
• 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.
Explicit Middleware:
• 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.
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.
i) Easy to write.
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.
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
• 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 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.
• */
• /**
• */
• }
• 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
• */
• {
• /**
• */
• }
• /**
• * 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.
• */
• /*
* This method creates the EJB Object.@return The newly created EJB Object.
• */
• javax.ejb.CreateException; }
65
H.T
• 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.
• */
• {
• /*
• */
• }
Bean Class:
package examples;
// EJB-required methods
• This is just about the most basic bean class possible. Notice:
• 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.
67
H.T
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.
• 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.
• 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.
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.
• 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
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:
• 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.
• 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.
• 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.
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.
• 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.
• Because entity bean data is uniquely identified in an underlying storage, entity beans
can also be found rather than created.
• 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.
• Entity contexts add the following methods on top of the generic EJB context.
74
H.T
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
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.
75
H.T
• 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).
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.
76
H.T
77
H.T
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