Core Course Vii J2Ee Technologies Objective
Core Course Vii J2Ee Technologies Objective
J2EE TECHNOLOGIES
Objective:
EJB: Session beans: Stateless and Statefull – Entity beans – CMP and BMP –
Message Driven Beans.
Introduction – Building a simple struts – Model layers –View layer – controller layer
– Validator – Tiles –Declarative Exception Handling –Struts Modules.
Text Books:
1. Jim Keogh “The Complete Reference J2EE “Tata McGraw – Hill Edition 2002. 2.
James Holmes “The Complete References Struts Second Edition “ Tata McGraw Hill
Edition-2007.
Reference Books:
1. Jusin Couch, Daniel H. Steinberg, “J2EE Bible” Wily India (P) Ltd, New Delhi
2002. 2. Paul Tremblett, “Instant Enterprise Java Y-Beans”, Tata McGraw Hill
Publishing Company, New Delhi, 2001.
*****
RMI (Remote Method Invocation)
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an
object running in another JVM.
The RMI provides remote communication between the applications using two
objects stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM.
Let's understand the stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests
are routed through it. It resides at the client side and represents the remote object.
When the caller invokes method on the stub object, it does the following tasks:
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the incoming
request, it does the following tasks:
At its core, the CORBA architecture for distributed objects shares many features
with the architecture used by Java RMI. A description of a remote object is used to
generate a client stub interface and a server skeleton interface for the object. A
client application invokes methods on a remote object using the client stub. The
method request is transmitted through the underlying infrastructure to the remote
host, where the server skeleton for the object is asked to invoke the method on the
object itself. Any data resulting from the method call (return values, exceptions) is
transmitted back to the client by the communication infrastructure.
But that’s where the similarities between CORBA and RMI end. CORBA was
designed from the start to be a language-independent distributed object standard,
so it is much more extensive and detailed in its specification than RMI is (or needs
to be). For the most part, these extra details are required in CORBA because it
needs to support languages that have different built-in features. Some languages,
like C++, directly support objects, while others, like C, don’t. The CORBA standard
needs to include a detailed specification of an object model so that nonobject-
oriented languages can take advantage of CORBA. Java includes built-in support
for communicating object interfaces and examining them abstractly (using Java
bytecodes and the Java Reflection API). Many other languages don’t. So the CORBA
specification includes details about a Dynamic Invocation Interface and a Dynamic
Skeleton Interface, which can be implemented in languages that don’t have their
own facilities for these operations. In languages that do have these capabilities, like
Java, there needs to be a mapping between the built-in features and the features as
defined by the CORBA specification.
The rest of this section provides an overview of the major components that make up
the CORBA architecture: the Interface Definition Language, which is how CORBA
interfaces are defined; the Object Request Broker (ORB) and Object Adaptor, which
are responsible for handling all interactions between remote objects and the
applications that use them; the Naming Service, which is a standard service in
CORBA that lets remote clients find remote objects on the network; and the inter-
ORB communication protocol, which handles the low-level communication between
processes in a CORBA context.
The Interface Definition Language provides the primary way of describing data types
in CORBA. IDL is independent of any particular programming language. Mappings,
or bindings, from IDL to specific programming languages are defined and
standardized as part of the CORBA specification. At the time of this writing,
standard bindings for C, C++, Smalltalk, Ada, COBOL, Lisp, Python and Java have
been approved by the OMG. Chapter 14 contains a complete description of IDL
syntax.
The central CORBA functions, services, and facilities, such as the ORB and the
Naming Service, are also specified in IDL. This means that a particular language
binding also specifies the bindings for the core CORBA functions to that language.
Sun’s Java IDL API follows the Java IDL mapping defined by the OMG standards.
This allows you to run your CORBA-based Java code in any compliant Java
implementation of the CORBA standard, provided you stick to standard elements of
the Java binding. Note, however, that Sun’s implementation includes some
nonstandard elements; they are highlighted in this chapter where appropriate.
The core of the CORBA architecture is the Object Request Broker, as shown
in Figure 4-1. Each machine involved in a CORBA application must have an ORB
running in order for processes on that machine to interact with CORBA objects
running in remote processes. Object clients and servers make requests through
their ORBs; the ORB is responsible for making the requests happen or indicating
why they can’t. The client ORB provides a stub for a remote object. Requests made
on the stub are transferred from the client’s ORB to the ORB servicing the
implementation of the target object. The request is passed on to the implementation
through an object adaptor and the object’s skeleton interface.
The skeleton interface is specific to the type of object that is exported remotely
through CORBA. Among other things, it provides a wrapper interface that the ORB
and object adaptor can use to invoke methods on behalf of the client or as part of
the lifecycle management of the object. The object adaptor provides a general facility
that “plugs” a server object into a particular CORBA runtime environment. Older
versions of the CORBA specification and Java IDL supported a Basic Object Adaptor
(BOA) interface, while newer versions (CORBA 2.3 and later, JDK 1.4 and later)
support a Portable Object Adaptor interface (we’ll discuss the difference later in the
chapter). All server objects can use the object adaptor to interact with the core
functionality of the ORB, and the ORB in turn can use the object adaptor to pass
along client requests and lifecycle notifications to the server object. Typically, an
IDL compiler is used to generate the skeleton interface for a particular IDL
interface; this generated skeleton interface will include calls to the object adaptor
that are supported by the CORBA environment in use.
The naming tree always starts with a root node, and subnodes of the object tree can
be created by an application. Actual objects are stored by name at the leaves of the
tree. Figure 4-2 depicts an example set of objects[12] registered within a Naming
Service directory. The fully qualified name of an object in the directory is the
ordered list of all of its parent nodes, starting from the root node and including the
leaf name of the object itself. So, the full name of the object labeled “Fred” is “Living
thing,” “Animal,” “Man,” “Fred,” in that order.
Each branch in the directory tree is called a naming context, and leaf objects
have bindings to specific names. Each node in the naming directory is represented
by an org.omg.CosNaming.NamingContext object. EachNamingContext can be
asked to find an object within its branch of the tree by asking for the object by
name, relative to that particular naming context. You can get a reference to the root
context of the naming directory from an ORB using the resolve_initial_references(
) method. Once you have a reference to the root of the naming directory, you can
perform lookups of CORBA objects, as well as register your own CORBA objects
with the Naming Service. We’ll see more concrete details of utilizing the CORBA
Naming Service later in this chapter in Putting It in the Public Eye.
Inter-ORB Communication
Version 2.0 (and later) of the CORBA standard includes specifications for inter-ORB
communication protocols that can transmit object requests between various ORBs
running on the network. The protocols are independent of the particular ORB
implementations running at either end of the communication link. An ORB
implemented in Java can talk to another ORB implemented in C, as long as they’re
both compliant with the CORBA standard and use the same CORBA
communication protocol. The inter-ORB protocol is responsible for delivering
messages between two cooperating ORBs. These messages might be method
requests, return types, error messages, etc. The inter-ORB protocol also deals with
differences between the two ORB implementations, like machine-level byte ordering
and alignment. As a CORBA application developer, you shouldn’t have to deal
directly with the low-level communication protocol between ORBs. If you want two
ORBs to talk to each other, you need to ensure that they are compatible in terms of
CORBA compliance levels (do they support similar levels of the CORBA
specification?) and that they both speak a common, standard inter-ORB protocol.
Why xml
The main thing which makes XML truly powerful is its international acceptance.
Many corporation use XML interfaces for databases, programming, office
application mobile phones and more. It is due to its platform independent feature.
XML is widely used in the era of web development. It is also used to simplify data
storage and data sharing.
If you need to display dynamic data in your HTML document, it will take a lot of
work to edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way you can focus on
using HTML/CSS for display and layout, and be sure that changes in the
underlying data will not require any changes to the HTML.
With a few lines of JavaScript code, you can read an external XML file and update
the data content of your web page.
In the real world, computer systems and databases contain data in incompatible
formats.
XML data is stored in plain text format. This provides a software- and hardware-
independent way of storing data.
This makes it much easier to create data that can be shared by different
applications.
XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.
Different applications can access your data, not only in HTML pages, but also from
XML data sources.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind
people, or people with other disabilities.
o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web
XML Example
The first line is the XML declaration. It defines the XML version (1.0) and the
encoding used (ISO-8859-1 = Latin-1/West European character set).
The next line describes the root element of the document (like saying: "this
document is a note"):
1. <note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body).
1. <to>Tove</to>
2. <from>Jani</from>
3. <heading>Reminder</heading>
4. <body>Don't forget me this weekend!</body>
Nowadays, most of the enterprise applications are using messaging concept for
asynchronous communication between heterogeneous applications using JMS or
AMQP. I’m going to deliver a series of posts to discuss these concepts in detail with
real-time examples in my coming posts.
JMS
The message is a piece of information. It can be a text, XML document, JSON data
or an Entity (Java Object) etc. The message is very useful data to communicate
between different systems.
What is Messaging?
What is JMS?
JMS stands for Java Message Service. JMS API is a Java API which contains a
common set of interfaces to implement enterprise based messaging systems. JMS
API is used to implement Messaging systems in Java-based applications only, it
does not support other languages.
JMS API is used to create, send, receive and read messages or exchange messages
between different systems. Once we develop a Java Messaging System with JMS
API, then we can deploy the same application in any JMS Provider software.
What is JSP?
Java Server Pages (JSP) is a technology which is used to develop web pages by
inserting Java code into the HTML pages by making special JSP tags. The JSP tags
which allow java code to be included into it are <% ----java code----%>.
It can consist of either HTML or XML (combination of both is also possible) with JSP
actions and commands.
It can be used as HTML page, which can be used in forms and registration pages
with the dynamic content into it.
Dynamic content includes some fields like dropdown, checkboxes, etc. whose value
will be fetched from the database.
JSP can be used for separation of the view layer with the business logic in the web
application.
JMS Architecture
An Enterprise Application may have ‘n’ number of components and they are
exchanging messages by using one of the Messaging System as shown below.
JMS Messaging System
Some Enterprise applications may have ‘n’ number systems and they exist in
different locations. They use different platforms. If they want to exchange
information in a loosely coupled manner, then we should use JMS Messaging
system.
JMS in Distributed Systems
JMS Advantages
JMS Components
JMS PROVIDER
S.NO. ORGANIZATION
SOFTWARE
1. WebSphere MQ IBM
5. HornetQ JBoss
Two-Tier Architecture:
The two-tier is based on Client Server architecture. The two-tier architecture is like
client server application. The direct communication takes place between client and
server. There is no intermediate between client and server. Because of tight
coupling a 2 tiered application will run faster.
Two-Tier Architecture
The above figure shows the architecture of two-tier. Here the direct communication
between client and server, there is no intermediate between client and server.
Let’s take a look of real life example of Railway Reservation two-tier architecture:
Let’s consider that first Person is making Railway Reservation for Mumbai to Delhi
by Mumbai Express at Counter No. 1 and at same time second Person is also try to
make Railway reservation of Mumbai to Delhi from Counter No. 2
If staff from Counter No. 1 is searching for availability into system & at the same
staff from Counter No. 2 is also looking for availability of ticket for same day then in
this case there is might be good change of confusion and chaos occurs. There might
be chance of lock the Railway reservation that reserves the first.
But reservations can be making anywhere from the India, then how it is handled?
So here if there is difference of micro seconds for making reservation by staff from
Counter No. 1 & 2 then second request is added into queue. So in this case the
Staff is entering data to Client Application and reservation request is sent to the
database. The database sends back the information/data to the client.
In this application the Staff user is an end user who is using Railway reservation
application software. He gives inputs to the application software and it sends
requests to Server. So here both Database and Server are incorporated with each
other, so this technology is called as “Client-Server Technology“.
The Two-tier architecture is divided into two parts:
Advantages:
In two tier architecture application performance will be degrade upon increasing the
users.
Cost-ineffective
Three-Tier Architecture:
Three-tier architecture typically comprise a presentation tier, a business or data
access tier, and a data tier. Three layers in the three tier architecture are as follows:
1) Client layer
2) Business layer
3) Data layer
1) Client layer:
It is also called as Presentation layer which contains UI part of our application. This
layer is used for the design purpose where data is presented to the user or input is
taken from the user. For example designing registration form which contains text
box, label, button etc.
2) Business layer:
In this layer all business logic written like validation of data, calculations, data
insertion etc. This acts as a interface between Client layer and Data Access Layer.
This layer is also called the intermediary layer helps to make communication faster
between client and data layer.
3) Data layer:
In this layer actual database is comes in the picture. Data Access Layer contains
methods to connect with database and to perform insert, update, delete, get data
from database based on our input data.
Three-tier Architecture
Three-tier Architecture
Advantages
Increase Complexity/Effort
Not only does your software gain from being able to get services at the best possible
rate, but it’s also easier to manage. This is because when you work on one section,
the changes you make will not affect the other functions. And if there is a problem,
you can easily pinpoint where it originates.
A More In-Depth Look at N-Tier Architecture
N-tier architecture would involve dividing an application into three different tiers.
These would be the
1. logic tier,
2. the presentation tier, and
3. the data tier.
Secure: You can secure each of the three tiers separately using different
methods.
Easy to manage: You can manage each tier separately, adding or modifying
each tier without affecting the other tiers.
Scalable: If you need to add more resources, you can do it per tier, without
affecting the other tiers.
Flexible: Apart from isolated scalability, you can also expand each tier in any
manner that your requirements dictate.
In short, with n-tier architecture, you can adopt new technologies and add more
components without having to rewrite the entire application or redesigning your
whole software, thus making it easier to scale or maintain. Meanwhile, in terms of
security, you can store sensitive or confidential information in the logic tier, keeping
it away from the presentation tier, thus making it more secure.
Two or more tiers can physically reside on the same Java Virtual Machine although
each tier provides a specific type of functionality to an application. Some of the APIs
of J2EE components can be used on more than one tier (i.e. XML API), while other
APIs (i.e., EJB API) or associated with a particular tier. Following diagram is
representing the multi-tier architecture of J2EE.
CLIENT TIER : Client tier consists of programs that interact with the user. It
prompts the user for input and then convert the user’s response into requests that
are forwarded to software on a component that processes the request and returns
results to the client program. J2EE clients can be classified as follows
Web client is A software (usually browser) that accesses resources located on the
web tier.
Ejb client can access one or more enterprise java beans that are located on the EJB
tier rather than resources on the web tier.
EIS clients are the interface between users and resources located on the EIS tier.
Multi-tier clients can access components located on tiers other than the tier where
the multi-tier client resides.
WEB TIER : Web tier accepts requests from other software that was sent using
POST, GET, and PUT operations, which are part of HTTP transmissions. The two
major components of web tier are Servlets and Java Server Pages. A servlet is a java
class that resides on the web tier and is called by a request from a browser client
that operates on the client tier. A servlet is associated with a URL that is mapped by
the servlet container. It typically generates an HTML output stream that is returned
to the web server. The web server in turn transmits the data to the client. JSP is
different than a servlet depending on the container that is used. JSP uses custom
tags to access the bean.
The version was called .Net framework 1.0. The .Net framework has come a long
way since then, and the current version is 4.7.1.
The .Net framework can be used to create both - Form-based and Web-based
applications. Web services can also be developed using the .Net framework.
The framework also supports various programming languages such as Visual Basic
and C#. So developers can choose and select the language to develop the required
application. In this chapter, you will learn some basics of the .Net framework.
Exception Handling - Exceptions are errors which occur when the application is
executed.
Examples of exceptions are:
If an application tries to open a file on the local machine, but the file is not present.
If the application tries to fetch some records from a database, but the connection to
the database is not valid.
Garbage Collection - Garbage collection is the process of removing unwanted
resources when they are no longer required.
Examples of garbage collection are
A File handle which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.
The database connection is no longer required. If the application has finished all
operations on a database, then the database connection may no longer be required.
Working with Various programming languages –
As noted in an earlier section, a developer can develop an application in a variety of
.Net programming languages.
Language - The first level is the programming language itself, the most common
ones are VB.Net and C#.
Compiler – There is a compiler which will be separate for each programming
language. So underlying the VB.Net language, there will be a separate VB.Net
compiler. Similarly, for C#, you will have another compiler.
Common Language Interpreter – This is the final layer in .Net which would be used
to run a .net program developed in any programming language. So the subsequent
compiler will send the program to the CLI layer to run the .Net application.
What is .NET Framework
2. Class Library
The .NET Framework includes a set of standard class libraries. A class library is a
collection of methods and functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level operations.
So there is a method which can be used to read the text from a file. Similarly, there
is a method to write text to a file.
Most of the methods are split into either the System.* or Microsoft.* namespaces.
(The asterisk * just means a reference to all of the methods that fall under the
System or Microsoft namespace)
A namespace is a logical separation of methods. We will learn these namespaces
more in detail in the subsequent chapters.
3. Languages
The types of applications that can be built in the .Net framework is classified
broadly into the following categories.
WinForms – This is used for developing Forms-based applications, which would run
on an end user machine. Notepad is an example of a client-based application.
ASP.Net – This is used for developing web-based applications, which are made to
run on any browser such as Internet Explorer, Chrome or Firefox.
The Web application would be processed on a server, which would have Internet
Information Services Installed.
Internet Information Services or IIS is a Microsoft component which is used to
execute an Asp.Net application.
The result of the execution is then sent to the client machines, and the output is
shown in the browser.
ADO.Net – This technology is used to develop applications to interact with
Databases such as Oracle or Microsoft SQL Server.
Microsoft always ensures that .Net frameworks are in compliance with all the
supported Windows operating systems.
Simplified deployment - The .Net framework also have tools, which can be used to
package applications built on the .Net framework. These packages can then be
distributed to client machines. The packages would then automatically install the
application.
UNIT III
Introduction to JSP
Introduction
In this JSP tags are used to insert JAVA code into HTML pages.
JSP is first converted into servlet by JSP container before processing the client’s
request.
Features of JSP
Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
Make Interactive websites :- In this we can create dynamic web pages which helps
user to interact in real time environment.
Portable, Powerful, flexible and easy to maintain :- as these are browser and server
independent.
Extension to Servlet :- as it has all features of servlets, implicit objects and custom
tags
JSP syntax
Syntax:-
Example:-
Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions.
Syntax:-
Example:-
JAVA Comments :- It contains the text that is added for information which has to
be ignored.
Syntax:-
Process of Execution
Create html page from where request will be sent to server eg try.html.
Start Tomcat
Run Application
<html>
<head>
</head>
<body>
</body>
</html>
o scriptlet tag
o expression tag
o declaration tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html file gets
the username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variable
methods. methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is pla
_jspService() method. _jspService() method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
Expression tags signal JSP to convert a Java statement – also called an expression –
into a string and display the output. Syntax options include the simple "<%= Java
statement %>" and the XML alternative "jsp:expression…."
Directives – or message tags – are instructional tags that contain two parts: type
and attribute. Type can be "page," which gives page-specific processing directions,
"Include," which provides specific file names or "Tag Library," which identifies the
tag library you want to use on the current page. Syntax options include the simple
"<%@ dir-type dir-attr %> and the XML alternative "."
Scriptlet tags allow you to embed any valid Java source code in JSP server pages.
The code within the tags executes in consecutive order on the server side and is
available for client access through a Web browser. Syntax options include the
simple "<% Java code %> and the XML alternative "jsp:scriptlet Java code."
Flow control tags function the same as – and are an alternative to – scriptlets.
Unlike scriptlets, however, flow control tags allow you to control the order in which
statements run. The conditional tags "if" and "choose" and the iterator tags
"forEach" and "forTokens" are all examples of JSP flow control tags. The syntax
framework for each includesJava code. For example, when you use an "if"
statement, the correct syntax isJava codewhere test= is the type and "$test
parameters" identifies tag attributes.
Action tags can tell JSP to transfer control between pages, set or get properties,
facilitate browser independent support for Java applets and make it possible to use
server-side JavaBeans. Of the many available action tags, the most common are the
include directive, the forward tag, which transfers control to a dynamic or static
URL and the useBean tag, which allows a JSP to create or receive an instance of a
reusable software component that works with Java called a JavaBean. The only
syntax option for an action tag is the XML version: "jsp:useBean Java body."
Comment tags are for "information only" and do not appear on JSP pages. Use them
for clarification or documentation and view them by right clicking on a Web page
and accessing the "view source" option. The only syntax option for a comment tag is
the simple version: <%/ comments go here />.
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each
request, it starts a new process.
Disadvantages of CGI
If the number of clients increases, it takes more time for sending the response.
For each request, it starts a process, and the web server is limited to start
processes.
Advantages of Servlet
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits over
the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as
follows:
Better performance: because it creates a thread for each request, not process.
Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle methods.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking the
init() method, Servlet comes in the ready state. In the ready state, servlet performs
all the tasks. When the web container invokes the destroy() method, it shifts to the
end state.
The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface. Syntax of the init method is given below:
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described
above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service method
of the Servlet interface is given below:
The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
POP: Acronym for Post Office Protocol. POP is the mechanism most people on the
Internet use to get their mail. It defines support for a single mailbox for each user.
RFC 1939 defines this protocol.
NNTP and Others:There are many protocols that are provided by third-party
providers. Some of them are Network News Transfer Protocol (NNTP), Secure
Multipurpose Internet Mail Extensions (S/MIME) etc.
The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as
JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is
divided into two main parts:
You can download latest version of JavaMail (Version 1.5.0) from Java's standard
website.
You can download latest version of JAF (Version 1.1.1) from Java's standard website.
Download and unzip these files, in the newly created top level directories you
will find a number of jar files for both the applications. You need to
add mail.jar and activation.jar files in your CLASSPATH.
SMTP server
To send emails, you must have SMTP server that is responsible to send mails.
You can use one of the following techniques to get the SMTP server:
Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James
server (Java Apache Mail Enterprise Server)etc. (or)
Use the SMTP server provided by the host provider for eg: free SMTP provide
by JangoSMTP site is relay.jangosmtp.net (or)
Use the SMTP Server provided by companies e.g. gmail, yahoo, etc.
The examples in the subsequent chapters, we've used the free JangoSMTP server to send
email. You can create an account by visiting this site and configure your email adress.
EJB: Session beans: Stateless and Statefull – Entity beans – CMP and BMP –
Message Driven Beans.
A session bean represents work performed by a singleclient. That work can be performed within a single method
invocation, or it may span multiple method invocations. If the work does span more than one method, the object must
retain the user’s object state across the method calls, and a stateful session bean would therefore be required.
Generally, stateless beans are intended to perform individual operations automatically and don’t maintain state across
method invocations. They’re also amorphous, in that any client can use any instance of a stateless bean at any time at
the container’s discretion. They are the lightest weight and easiest to manage of the various EJB component
configurations.
Stateful session beans maintain state both within and between transactions. Each stateful session bean is therefore
associated with a specific client. Containers are able to save and retrieve a bean’s state automatically while managing
Stateful session beans maintain data consistency by updating their fields each time a transaction is committed. To
keep informed of changes in transaction status, a stateful session bean implements the SessionSynchronization
interface. The container calls methods of this interface while it initiates and completes transactions involving the
bean.
Session beans, whether stateful or stateless, are not designed to be persistent. The data maintained by stateful session
beans is intended to be transitional. It is used solely for a particular session with a particular client. A stateful session
bean instance typically can’t survive system failures and other destructive events. While a session bean has a
container-provided identity (called its handle), that identity passes when the client removes the session bean at the
end of a session. If a client needs to revive a stateful session bean that has disappeared, it must provide its own means
A stateful session bean will maintain a conversational state with a client. The state of the session is maintained for the
duration of the conversation between the client and the stateful session bean. When the client removes the stateful
session bean, its session ends and the state is destroyed. The transient nature of the state of the stateful session bean
should not be problematic for either the client or the bean, because once the conversation between the client and the
stateful session bean ends, neither the client nor the stateful session bean should have any use for the state.
A stateless session bean will not maintain conversational states for specific clients longer than the period of an
individual method invocation. Instance variables used by a method of a stateless bean may have a state, but only for
the duration of the method invocation. After a method has finished running either successfully or unsuccessfully, the
states of all its instance variables are dropped. The transient nature of this state gives the stateless session bean
Bean pooling Any stateless session bean method instance that is not currently invoked is equally available
to be called by an EJB container or application server to service the request of a client. This allows the EJB
when applications have a large number of clients. When compared to stateful session beans, stateless session
Performance An EJB container will never move a stateless session bean from RAM out to a secondary
storage, which it may do with a stateful session bean; therefore, stateless session beans may offer greater
Since no explicit mapping exists between multiple clients and stateless bean instances, the EJB container is free to
service any client’s request with any available instance. Even though the client calls
the create() and remove()methods of the stateless session bean, making it appear that the client is controlling the
lifecycle of an EJB, it is actually the EJB container that is handling the create() and remove() methods without
Entity beans
- No code for database code is needed(by placing the specific accessibility is provided by
XML file).
- The code reusability is needed.
- The speed of development by creation of the database access code by the developers.
- To provide the flexibility for the bean developer to perform the persistence operations.
- The persistent storage is a non database system or is a legacy database system that does
not supports for CMP.
3. Author the source code for the entity bean, which involves developing the following:
5. Create the database tables. (If your database tables already exist, you can omit this step)
7. Compile and archive all the EJB components into a JAR file.
2. Get the mapping done for the entity beans for the appropriate database tables and save
the mapping information that is a deployable XML file.
1. Configuration :
2. Code generation :
- The information from the configuration phase is used by the different tools to generate the
classes for the required beans.
- This process may include helper classes related to transactions, persistence, and security.
- The implementations of EJBHome and EJBObject, and the stubs and skeletons required for
RMI-IIOP.
3. Installation :
- The EJB server is started and make the beans available to the clients applications.
- The life of a bean’s instance starts with a set of files. These files include remote interface,
interface, deployment descriptor, primary key and the needed files at the time of
deployment.
- At the time of starting the EJB server,with the help of the method Class.newInstance() , all
the instances are created and placed in a pool. The default values of the persistent fields are
set. The bean class should never contain the constructor. Therefore the default no-argument
must be available in the container.
- Before placing the instances in the pool, an instance EntityContext is assigned by the
container which assigns and implements the setEntityContext() method by the bean class,
followed by entering into the instance pool.
- Now the bean instance is available for the client requests and become active soon after
receiving the requests. The bean container provides different levels of access at every stage
of the bean’s life cycle.
- Once the bean reaches this state, it can accept the requests from the client. The state of a
beans instance reaches to ready state once the container assigns it to an EJB object.
- The life of a bean’s instance comes to an end when the container decides to remove it from
the pool and allows it to be garbage collected.
- This may happen when the container decides to reduce the number of instances from the
pool in order to conserve the resources. So that the highest performance can be achieved.
- All the logic for synchronizing the bean's state with the database is handled automatically by the container.
- The bean developer doesn't need to write any data access logic.
- The EJB server is supposed to take care of all the persistence needs automatically.
- Vendor tools are used to map the entity fields to the database and absolutely no database access code is writ
bean class.
- Enterprise bean manages synchronizing its state with the database as directed by the container.
- BMP gives the bean developer the flexibility to perform persistence operations that are too complicated for the
container or to use a data source that is not supported by the container.
- The bean uses a database API to read and write its fields to the database, but the container tells it when to do
synchronization operation and manages the transactions for the bean automatically.
A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This
type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages
instead of events. The messages can be sent by any Java EE component (an application client, another enterprise bean, or
a web component) or by a JMS application or system that does not use Java EE technology. Message-driven beans can
process JMS messages or other kinds of messages.
A message-driven bean’s instances retain no data or conversational state for a specific client.
All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any
message-driven bean instance. The container can pool these instances to allow streams of messages to be processed
concurrently.
A single message-driven bean can process messages from multiple clients.
The instance variables of the message-driven bean instance can contain some state across the handling of client
messages, such as a JMS API connection, an open database connection, or an object reference to an enterprise bean
object.
Client components do not locate message-driven beans and invoke methods directly on them. Instead, a client accesses a
message-driven bean through, for example, JMS by sending messages to the message destination for which the message-
driven bean class is the MessageListener. You assign a message-driven bean’s destination during deployment by
using GlassFish Server resources.
A message can be delivered to a message-driven bean within a transaction context, so all operations within
the onMessage method are part of a single transaction. If message processing is rolled back, the message will be
redelivered. For more information, see Chapter 25, A Message-Driven Bean Example and Chapter 44, Transactions.
Introduction – Building a simple struts – Model layers –View layer – controller layer
– Validator – Tiles –Declarative Exception Handling –Struts Modules.
Struts
The struts framework is used to develop MVC-based web application.
Model − The lowest level of the pattern which is responsible for maintaining data.
View − This is responsible for displaying all or a portion of the data to the user.
Controller − Software Code that controls the interactions between the Model and
View.
MVC is popular as it isolates the application logic from the user interface layer and
supports separation of concerns. Here the Controller receives all requests for the
application and then works with the Model to prepare any data needed by the View.
The View then uses the data prepared by the Controller to generate a final
presentable response. The MVC abstraction can be graphically represented as
follows.
Struts2 is a popular and mature web application framework based on the MVC
design pattern. Struts2 is not just a new version of Struts 1, but it is a complete
rewrite of the Struts architecture.
The Webwork framework initially started with Struts framework as the basis and
its goal was to offer an enhanced and improved framework built on Struts to
make web development easier for the developers.
After a while, the Webwork framework and the Struts community joined hands
to create the famous Struts2 framework.
POJO Forms and POJO Actions − Struts2 has done away with the Action Forms
that were an integral part of the Struts framework. With Struts2, you can use any
POJO to receive the form input. Similarly, you can now see any POJO as an Action
class.
Tag Support − Struts2 has improved the form tags and the new tags which allow
the developers to write less code.
AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and
has integrated AJAX support into the product by creating AJAX tags, this function is
very similar to the standard Struts2 tags.
Easy Integration − Integration with other frameworks like Spring, Tiles and
SiteMesh is now easier with a variety of integration available with Struts2.
Profiling − Struts2 offers integrated profiling to debug and profile the application. In
addition to this, Struts also offers integrated debugging with the help of built in
debugging tools.
Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker
templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS
knowledge is enough to modify the tags.
Promote Less configuration − Struts2 promotes less configuration with the help of
using default values for various settings. You don't have to configure something
unless it deviates from the default settings set by Struts2.
View Technologies − Struts2 has a great support for multiple view options (JSP,
Freemarker, Velocity and XSLT)
Struts 2 Disadvantages
Though Struts 2 comes with a list of great features, there are some limitations
of the current version - Struts 2 which needs further improvement. Listed are
some of the main points −
Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with
the standard JSP, Servlet APIs and a large & elaborate framework.
Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has
fewer online resources, and many first-time users find the online Apache
documentation confusing and poorly organized.
Less Transparent − With Struts applications, there is a lot more going on behind
the scenes than with normal Java-based Web applications which makes it difficult to
understand the framework.
Final note, a good framework should provide generic behavior that many
different types of applications can make use of it.
Struts 2 is one of the best web frameworks and being highly used for the
development of Rich Internet Applications (RIA).
Struts MVC
The Model
The model is responsible for managing the data of the application. It responds to
the request from the view and it also responds to instructions from the controller to
update itself.
The View
The Controller
The controller is responsible for responding to the user input and perform
interactions on the data model objects. The controller receives the input, it validates
the input and then performs the business operation that modifies the state of the
data model.
Struts2 is a MVC based framework. In the coming chapters, let us see how we can
use the MVC methodology within Struts2.
Struts2 is a popular and mature web application framework based on the MVC
design pattern. Struts2 is not just a new version of Struts 1, but it is a complete
rewrite of the Struts architecture.
The Webwork framework initially started with Struts framework as the basis and
its goal was to offer an enhanced and improved framework built on Struts to
make web development easier for the developers.
After a while, the Webwork framework and the Struts community joined hands
to create the famous Struts2 framework.
POJO Forms and POJO Actions − Struts2 has done away with the Action Forms
that were an integral part of the Struts framework. With Struts2, you can use any
POJO to receive the form input. Similarly, you can now see any POJO as an Action
class.
Tag Support − Struts2 has improved the form tags and the new tags which allow
the developers to write less code.
AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and
has integrated AJAX support into the product by creating AJAX tags, this function is
very similar to the standard Struts2 tags.
Easy Integration − Integration with other frameworks like Spring, Tiles and
SiteMesh is now easier with a variety of integration available with Struts2.
Plugin Support − The core Struts2 behavior can be enhanced and augmented by
the use of plugins. A number of plugins are available for Struts2.
Profiling − Struts2 offers integrated profiling to debug and profile the application. In
addition to this, Struts also offers integrated debugging with the help of built in
debugging tools.
Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker
templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS
knowledge is enough to modify the tags.
Promote Less configuration − Struts2 promotes less configuration with the help of
using default values for various settings. You don't have to configure something
unless it deviates from the default settings set by Struts2.
View Technologies − Struts2 has a great support for multiple view options (JSP,
Freemarker, Velocity and XSLT)
Struts 2 Disadvantages
Though Struts 2 comes with a list of great features, there are some limitations
of the current version - Struts 2 which needs further improvement. Listed are
some of the main points −
Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with
the standard JSP, Servlet APIs and a large & elaborate framework.
Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has
fewer online resources, and many first-time users find the online Apache
documentation confusing and poorly organized.
Less Transparent − With Struts applications, there is a lot more going on behind
the scenes than with normal Java-based Web applications which makes it difficult to
understand the framework.
Final note, a good framework should provide generic behavior that many
different types of applications can make use of it.
Struts 2 is one of the best web frameworks and being highly used for the
development of Rich Internet Applications (RIA).
Actions
Interceptors
View technologies
Struts 2 is slightly different from a traditional MVC framework, where the action
takes the role of the model rather than the controller, although there is some
overlap.
The above diagram depicts the Model, View and Controller to the Struts2 high
level architecture. The controller is implemented with a Struts2 dispatch servlet
filter as well as interceptors, this model is implemented with actions, and the
view is a combination of result types and results. The value stack and OGNL
provides common thread, linking and enabling integration between the other
components.
Apart from the above components, there will be a lot of information that relates
to configuration. Configuration for the web application, as well as configuration
for actions, interceptors, results, etc.
User sends a request to the server for requesting for some resource (i.e. pages).
The Filter Dispatcher looks at the request and then determines the appropriate
Action.
Finally, the result is prepared by the view and returns the result to the user.
In this way, we need to put code in try-catch block. If the exception is caught in the try block, the
control flows into catch block, where we add the errors into the messages and put it in the
session. Then the control is forwarded manually to the error-page where the warning message is
displayed. The drawback of this method, is the developer is fully responsible for the various flow
of applications where the chance of misleading is high.
Struts Tutorial
Struts Basics
Struts Action & FormBeans
Struts Modules
Struts Validation Framework
Struts Tiles Tutorial
Exception/Error Handling In Struts
The declarative exceptions can be placed as action-specific or global. In action specific, we define
these exceptions and path inside the action tag. Otherwise, the exceptions are defined inside the
global-exception tag. This would mean that, if this exception arises in any action class, it would
automatically forwarded to the specified path known as error-page. The error-page then shows the
exact warning message.
3 <exception key="error.invalid.Password"
In the above code exceptions will be handled during the login action.
Entry in ApplicationResources.properties
?
1 <global-exceptions>
2 <exception
3 type=”com.javawebtutor.NoResultFoundException”
4 key=”error.NoResultFound.Exception”
5 path=”/noresultpage.jsp”/>
</global-exceptions>
6
There are two ways in which you can specify the Tiles definition and their
attributes. One is using JSP Tile Definition and the other way is using XML Tile
Definition.
All JSP pages that uses Tiles should have the following taglib extension.
Lets first design the base layout page using tiles. The base layout page is a
normal jsp page, which defines different sections. A region is defined using
the <tiles:insert> tag. The attribute value hold the name of the region.
The layout shown above can be created using the following code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:getAsString name="title" ignore="true" /></title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="20%" colspan="2">
<tiles:insert attribute="header" ignore="true" />
</td>
</tr>
<tr>
<td width="20%" height="250">
<tiles:insert attribute="menu" />
</td>
<td>
<tiles:insert attribute="body" />
</td>
</tr>
<tr>
<td height="20%" colspan="2">
<tiles:insert attribute="footer" />
</td>
</tr>
</table>
</body>
</html>
If the ignore attribute is set to true, then that region is optional. Even if the
attribute is not specified the code will work fine.
To create our home page we need to insert title, header, menu, body and footer
jsp pages. The following code is used to create our home page.
The name attribute of the put tag specifies the region in the baseLayout in
which the corresponding page specified by the value attribute should be
displayed. In our example the header region is occupied by the header.jsp page,
the menu part is occupied by the menu.jsp page, the body part by the body.jsp
page and the footer by the footer.jsp page. The only section that will be
changing when the user request a different page is the body part.
On executing the application the following home page is displayed. The table
border is set to 1 inorder to give a clear seperation between the regions.
On clicking the links in the left menu, only the body part of the page should
change. So instead of forwarding each link to a jsp page, we forward it to a Tile
definition.
tiles-defs.xml file contains all the Tile definitions. A Tile definition can be
added in the following way.
<html>
<body>
<a href="Link.do?method=friends" >Friends</a><br>
<a href="Link.do?method=office" >The Office</a>
</body>
</html>
<action-mappings>
<action path="/Link" parameter="method" type="com.vaannila.LinkAction">
<forward name="friends" path="friends"/>
<forward name="office" path="office"/>
</action>
</action-mappings>
The path attribute hold the value of the Tile definition to forward. When the
path value is "friends" the baseLayout.jsp page is displayed with the tilte as
Friends and friends.jsp as the body.
When the path value is "office" the baseLayout.jsp page is displayed with the
tilte as The Office and office.jsp as the body.
Struts Modules:
When you develop a web based application using struts,many developers like to put all Struts related
stuff (action, form) into a single Struts configuration file for the entire application .For small application
its not a problem.But if you are developing big application day by day your configuration file will
become complicated.
Generally a large application will be divided into various modules.These modules will be developed
by various teams and finally when you are integrating each module, you may feel it as complex task.
Apache has analysed all these problems and introduced Struts Modules which allows you to
develop modularized struts application.Struts modules concept allows you to write Struts
Configuration file for each module.
index.jsp
?
1 <html>
2 <body>
4 </body>
</html>
5
info.jsp
?
1 <html>
2 <body>
4 </body>
</html>
5
Now create Struts configuration files for the application.Here we are going to create two configuration
files.We can create any number of configuration files.
struts-config1.xml
?
10parameter="/index.jsp"/>
</action-mappings>
11
</struts-config>
12
struts-config2.xml
?
11</action-mappings>
12</struts-config>
Now we need to map both the configuration files in web.xml separated by comma.
web.xml
?
1
<!DOCTYPE web-app PUBLIC
2
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3
"<a class="vglnk" href="http://java.sun.com/dtd/web-app_2_3.dtd"
4 rel="nofollow"><span>http</span><span>://</span><span>java</span><span>.</span><span>sun<
</span><span>app</span><span>_</span><span>2</span><span>_</span><span>3</span><span>.</s
5
<web-app>
6 <display-name>Maven Struts Examples</display-name>
7 <servlet>
8 <servlet-name>action</servlet-name>
9 <servlet-class>
org.apache.struts.action.ActionServlet
10
</servlet-class>
11
<init-param>
12
<param-name>config</param-name>
13
<param-value>
14
/WEB-INF/struts-config-1.xml, /WEB-INF/struts-config-2.xml
15</param-value>
16</init-param>
17<load-on-startup>1</load-on-startup>
18</servlet>
19<servlet-mapping>
<servlet-name>action</servlet-name>
20
<url-pattern>*.do</url-pattern>
21
</servlet-mapping>
22
</web-app>
23
If you are working with multiple modules in your project, then you have to create one configuration file
for each modules. Let's say the project has two modules Employee and Reports.Here Employee and
Department are two different modules
Lot of fields that we validate require same logic to validate them.you need to write same code
repeatedly in every validate() method hence code is unnecessarily duplicated.
To avoid this problem and to simplify the validation handling, Apache has introduced validation
framework.Validation framework is not a part of struts frame work ,it should be integrated into the
struts explicitly.
The Validator framework allows us to move all the validation logic completely outside
of the ActionForm and declaratively configure it for an application through external
XML files.
The Validator Framework in Struts consist of two XML configuration files. The first one
is the validator-rules.xml file which contains the default Struts pluggable validator
definitions.If you want to create new validation, You can add new validation rules by
adding an entry in this file.
The second one is the validation.xml file which contain details regarding the
validation rules that are applied to the different Form Beans. These two configuration
file should be place inside the /WEB-INF folder of the application.