Component Technology Notes 4 PDF
Component Technology Notes 4 PDF
Component Technology Notes 4 PDF
UNIT-IV THE
SUN WAY
Components variety – Applets, Servlets, Java beans, enterprise beans – EJB
architecture – Types of beans – Characteristics – Building and deploying distributed
applications using EJB.
4.1 APPLETS
Applets are the first Component model introduced by Java.
A Java applet is a small application written in Java, and delivered to users in the
form of byte code.
The user launches the Java applet from a web page.
The Java applet then executes within a Java Virtual Machine (JVM) in a process separate
from the web browser itself, yet it can appear in a frame of the web page, in a new
application window, or in Sun's Applet Viewer, a stand-alone tool for testing applets.
Java applets are executed in a sandbox by most web browsers, preventing them from
accessing local data like clipboard or file system.
The code of the applet is downloaded from a web server and the browser either
embeds the applet into a web page or opens a new window showing the applet's user
interface.
A Java applet extends the class java.applet.Applet. The class must override methods
from the applet class to set up a user interface.
Since Java’s byte code is platform independent, Java applets can be executed by browsers
for many platforms, including Microsoft windows, UNIX, Mac os and Linux.
4.2 SERVLETS
The second Java component model is Servlets.
The Servlet is a Java programming languageclass used to extend the capabilities of a
server.
A Servlet is an object that receives a request and generates a response based on that
request.
Servlets are most often used to:
o Process or store data that was submitted from an HTML form
o Provide dynamic content such as the results of a database query
o Manage state information that does not exist in the stateless HTTP protocol
To deploy and run a Servlet, a web container must be used.
A web container is essentially the component of a web server that interacts with the
servlets.
The web container is responsible for managing the lifecycle of servlets, mapping a URL
to a particular servlet and ensuring that the URL requester has the correct access rights.
Servlets can be generated automatically from Java Server Pages (JSP) by the Java
Server Pages compiler.
The difference between servlets and JSP is that servlets typically embed HTML inside
Java code, while JSPs embed Java code in HTML.
Three methods are central to the life cycle of a servlet. These are init(), service(), and
destroy(). They are implemented by every servlet and are invoked at specific times by the
server.
During initialization stage of the servlet life cycle, the web container initializes the
servlet instance by calling the init() method, passing an object implementing the
javax.servlet.ServletConfig interface.
After initialization, the servlet instance can service client requests The web container
calls the service() method of the servlet for every request.
The service() method determines the kind of request being made and dispatches it to
an appropriate method to handle the request.
Finally, the web container calls the destroy() method that takes the servlet out of service.
The destroy() method, like init(), is called only once in the lifecycle of a
servlet.
4.3 JAVABEANS
The third component model of Java is the Java beans.
A Java Bean is a reusable software component that can be manipulated visually in a
builder tool.
The builder tools may include web page builders, GUI layout builders. Sometimes the
“builder tool” may simply be a document editor.
Some Java Beans may be simple GUI elements such as buttons and sliders. Other
Java Beans may be visual software components such as database viewers, or data feeds.
Beans are appropriate for software components that can be visually manipulated and
customized to achieve some effect
They are classes that encapsulate many objects into a single object (the bean). They
are serializable, have a 0-argument constructor, and allow access to properties using
getter and setter methods
Java beans focuses on “Connection – Oriented programming” between a client and a
server.
Java beans are very useful in building client-side applications.
They explicitly support a visual application design mode.
4.3.1.1 Properties
Properties are named attributes associated with a bean that can be read or written by
calling appropriate methods on the bean.
Properties show up in a number of ways:
1. Properties may be exposed in scripting environments as though they
were fields of objects.
2. Properties can be accessed programmatically by other components
calling their getter and setter methods
3. Typically a bean’s properties will be persistent, so that their state will be
stored away as part of the persistent state of the bean.
4.3.1.2 Methods
The Methods a Java Bean exports are just normal Java methods which can be called
from other components or from a scripting environment
For readable properties there will be a getter method to read the property value. For
writable properties there will be a setter method to allow the property value to be
updated.
For simple properties the accessor type signatures are:
o void setFoo(PropertyType value); // simple setter
o PropertyTypegetFoo(); // simple getter
4.3.1.3 Events
Events provide a way for one component to notify other components that something
interesting has happened.
Events are one of the core features of the Java Beans architecture.
Events provide a convenient mechanism for allowing components to be plugged
together in an application builder.
Events are a mechanism for propagating state change notifications between a source
object and one or more target listener objects.
Event State Objects
Information associated with a particular event notification is normally encapsulated in
an “event state” object that is a subclass of java.util.EventObject.
1. EJB components are server-side components written entirely in the Java programming
language.
2. System level services such as Transactions, security, life-cycle, threading, persistence
etc., are automatically managed for the EJB component by the EJB server.
3. EJB architecture is absolutely transactionl, distributed, portable, multi-tier, scalable
and secure.
4. EJB components are fully portable across any server and any os, work with any client.
5. Four major parts of bean are
The home interface.
The remote interface.
The implementation class.
The XML deployment descriptor.
1. Incoming requests need to be accepted, checked for proper authorization, and routed
to appropriate components which are ready to handle a particular request.
2. Such components need to draw the information sources to retrieve or synthesize the
requested contents.
3. The retrieved contents need to be sent to the requesting party.
These three steps are handled by a web server.
Client Web C
Machine G Requested
Server
I
Static HTML HTML
Fig.4.1 working of web server
4.4.7 ASP:
For handling bulk of website requirements, Microsoft introduces ASP (Active Server
Pages).
ASP allows raw web pages to include server-side script code.
The ASP server executes such scripts and produces HTML fragments as result.
ASP then places the HTML fragments on the script and returns the resulting HTML
page to the client.
4.4.8 JSP:
JSP (Java Server Pages) was improved on the ASP model. JSP are pages containing
HTML pages with inserted java fragments.
JSP pages are compiled into servlets.
A JSP server activates servlets to handle the requests.
At the level of servlets, HTML resides inline in Java source code.
The following example of servlet produces a HTML result.
importjavax.servlet.*;
importjavax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException,java.io.IOException
{
java.util.calender calendar = new java.util.GregorianCalender();
int hour = calendar.get(currTime.Hour);
int minute = calendar.get(currTime.Minute);
ServletOutputStream out = response.getWriter();
out.print(“<HTML><BODY>\r\n”);
out.print(“The time is:”+hour+”:”+minute+\r\n);
Department of Information Technology, SMVEC Page90
ITT73 COMPONENT TECHNOLOGY
out.print(“</BODY></HTML>\r\n”);
}
}
The servlet container supports servlets by providing access to HTTP request
parameters and by managing sessions.
JSP embeds the source code within the markup language. The content of
<%.......%>tags is interpreted as Java source code.
In case of large pieces of Java code in JSP page, it is preferable to keep the code in
separate java packages and reduce code.
JSP servlets can be used to implement simple web services by combining servlets
with libraries.
JSP server is combined with web service protocols such as SOAP to implement web
service.
Servlets do not directly produce the output by the server to the client.
Instead, a request can be handled by one server containing business logic.
After processing, the servlet can handover output generation to another servlet class.
Composed of server software, the EJB server is analogous to the Object Request
Broker (ORB) from the CORBA world.
The server provides a way for the client to transact with the EJBs. It also provides
naming services.
The directory/naming service provides the ability to locate any object registered with
the directory/naming service.
It provides a mapping between a given name of an entity and, in the case of EJBs, a
stub that corresponds to the home interface of an Enterprise Java Bean.
The home interface declares the methods for creating, finding, and destroying
instances of EJBs.
The methods declared in the home interface must correspond to certain methods
implemented in the bean class.
The remote interface declares the methods that contain the EJB's business logic.
The methods declared in the remote interface must be implemented in the bean class.
If the EJB is named Demo, then the remote interface should be Demo.java, the home
interface should be DemoHome.java, and the bean class should be either DemoBean.java or
DemoEJB.java. The deployment descriptor should always be ejb-jar.xml.
In figure 4.4, a client can use a stub to remotely invoke exposed methods of an object
that exists in a location separate from the client.
The stub will receive the return value from the method invoked from the remote
object and pass the value to the client, if a value is returned.
1. Session beans
2. Entity bean
3. Message-driven bean or Message beans
Session beans are used to represent non-persistent business logic. They almost always
have an association with a particular client. If the container is shutdown, the session beans
running are lost. Session beans can access and modify persistent data, though entity beans are
usually more suitable for working with persistent data.
It is of two types
1. Stateless bean
2. Stateful bean
Stateless bean
1. A stateless session bean does not maintain state across multiple invocations.
2. The container decides to keep the instance in a pool instead of creating new ones for
every invocation in every session.
3. A stateless session bean does not maintain a conversational state with the client.
4. When a client invokes the methods of a stateless bean, the bean’s instance variables
may contain a state specific to that client, but only for the duration of the invocation.
5. When the method is finished, the client-specific state should not be retained.
6. Clients may, however, change the state of instance variables in pooled stateless beans,
and this state is held over to the next invocation of the pooled stateless bean.
7. Except during method invocation, all instances of a stateless bean are equivalent,
allowing the EJB container to assign an instance to any client. The state of a stateless
session bean should apply across all clients.
A stateless session bean can implement a web service, but other types of enterprise beans
cannot.
1. A stateful session bean remains associated with one session for the lifetime.
2. The state of an object consists of the values of its instance variables.
3. The bean can retain state across method invocations
4. In a stateful session bean, the instance variables represent the state of a unique client-
bean session.
5. Because the client interacts (“talks”) with its bean, this state is often called
theconversational state.
6. The state is retained for the duration of the client-bean session.
7. If the client removes the bean or terminates, the session ends and the state disappears.
<session>
<ejb name>….name of the session bean….</ejb name>
<home>….name of the EJB home interface..</home>
<remote>…name of object interface…</remote>
<local-home>…name of local EJB home interface…</local-home>
<local>…name of local EJB object interface…</local>
<ejb-class>…name of class implementing this Ejb…</ejb-class>
<session-type>…Stateless or Stateful…</session-type>
<transaction-type>..container or bean…</transaction-type>
<ejb-ref>..import of other beans referenced by this bean….</ejb-ref>
<security-identity>…use caller-identity…</security-identity>
</session>
The descriptor assigns name to the bean, home interface and object interface.
The EJB class is the main class implementing the bean.
The session-type determines whether it is a stateful or stateless bean, therefore
whether the container will create new instance per call or not.
Session bean undergoes two types of transaction
Bean-managed transaction(optional)
Container-managed transaction(default)
The EJB reference lists out names of other beans and their local and remote EJB
home and remote interfaces.
Finally, the security identity field allows a bean to run under caller’s identity or under
some specified roles.
An entity bean uses database objects to encapsulate access to actual database records.
Entity Beans always have states. Each Entity Bean may however be shared by
multiple EJB Clients. Their states can be persisted and stored across multiple
invocations. Hence they can survive System Shutdowns.
An "Entity Bean" is a type of Enterprise JavaBean, a server-side J2EEcomponent, that
represents persistent data maintained in a database.
An entity bean corresponds to a single row in a relational table or it corresponds to a
row in the result of a Join operation.
The mapping of entity beans to and from database rows is called persistence.
Entity beans can manage their own persistence by directly using JDBC to operate
over databases.
<entity>
<ejb name>…name of entity bean….</ejb name>
<home>…name of ejb home interface..</home>
<remote>…name of ejb object interface…</remote>
<local-home>…name of local ejb home interface</local-home>
<local>…name of ejb object interface…</local>
<ejb-class>…name of class implementing this ejb…</ejb-class>
<persistence-type>…container or bean…</persistence-type>
<primary-key class>….</primary-key class>
<reentrant>true or false</reentrant>
<abstract schema name>…..</abstract schema name>
<prim-key-field>…field name…</prim-key-field>
….
</entity>
The initial fields are same as session bean descriptors.
The re-entrant field can be used to enable re-entnrant calls, by default; this is prohibited
and causes the container to throw an exception.
Disadvantages:
It is not possible to select rows in sorted order.
It is not possible to properly handle dates.
The lack of support for sorted order is a significant drawback for high performance
applications.
4.6.7 JMS:
Java message service.
JMS is a Java access mechanism to messaging systems.
It implements 2 types of messaging
point-to-point
Broadcast.
Point-to-point message queues supports delivery of messages between client and queue.
In broadcast, messages published to a particular topic are delivered to all subscribers of
that topic.
Advantages:
It is possible to write all application logic using md-beans.
Well-suited for workflow-oriented automatic distribution of work-items.
Disadvantages:
Message-queue oriented designed is fully asynchronous and thus not suitable for
serving interactive sessions.
Distributed Application
A distributed application is software that is executed or run on multiple computers
within a network. These applications interact in order to achieve a specific goal or task.
Traditional applications relied on a single system to run them. Even in the client- server
model, the application software had to run on either the client, or the server that the client was
accessing. However, distributed applications run on both simultaneously.
With distributed applications, if a node that is running a particular application goes
down, another node can resume the task.
Building and Deploying an Application using EJB
The following are the steps involved in creating and deploying an application using EJB.
1. Create a Remote interface of Bean.
2. Create Bean’s home interface.
3. Create Bean’s implementation class.
4. Compile home interface, remote interface & implementation class.
5. Create a session descriptor.
6. Create a manifest.
7. Create aejb-jar file.
8. Deploy the ejb-jar file.
9. Write a client.
10. Run the client.
Steps
The home interface is the client’s initial point of contact with EJB components.
The client obtains a reference to an object implementing the home interface via JNDI.
After the client has obtained this reference, it can use a create() method to obtain a
reference to an object that implements the remote interface.
packagemyprogram.Helloejb;
importjavax.ejb;
publicinterfaceHelloHome extends EJBHome
{
public Hello create() throws java.rmi.RemoteException, javax.ejb.CreateException;
}
The create() method is similar to constructors, that initializes an object, thereby
allowing the container implementers to avoid overhead of instantiating a new object
each time a client requests a reference.
packagemyprogram.HElloejb;
importjavax.ejb;
public class helloBean implements SessionBean
{ SessionContextctx;
public void ejbCreate()
{
}
public String sayHello(String s)
{
return “Hello there,”+s;
}
public void ejbRemove()
{
}
public void ejbpassivate()
{
}
public void ejbactivate()
{
}
public void setSessionContext(sessionContextctx)
{
this.ctx=ctx;
}
HelloBean implements the session bean interface, because we are using a session
bean.
A class variable is declared to hold the reference to sessionContext variable. The
Bean uses the session context to interact with the container.
ejbRemove() method is called by the container to notify the EJB instance that it
will be removed soon.
ejbpassivate() and ajbactivate() are called by the container to swap put ejb
instances to temporary storage and vice-versa.
6. Create a Manifest:
A Manifest file is a text document that contains information about the contents of a jar
file.
For an ejb.jar file a pair of lines must be added.
o Name: EJB/sample/myprogram/Helloejb.ser
o Enterprise-Bean : True.
The server loads your EJB and make it ready for use.
9. Write a client:
importmyprogram.Helloejb.*;
importjava.rmi.*;
importjavx.rmi.naming.*;
public class Helloclient
{public static void main(String[] args)
{try{
InitialContextic=new InitialContext();
HelloHome home=(Hellohome)ic.lookup(“HelloHome”);
Hello hel=home.create();
String retval=hel.sayHello(“Tom”);
System.out.println(“returned:”+retval);
hel.remove();
}
catch(java.rmi.RemoteException e)
{
System.out.println(“remote exception occurred:”+e);
}catch(java.ejb.CreateException e){
System.out.println(“Create Exception occurred:”+e);
}}}
The client uses JNDI classes to lookup a reference to EJB object’s home interface.
The initial context class serves as an client’s interface to JNDI.
Create() of method is invoked on the home interface to obtain reference to an object
that implements bean’s remote interface.
Following the logic are a number of catch blocks to handle any exceptions that might
be thrown in the process of looking up, creating, removing the remote bean.
Say Hello()
Say Hello()
Say Hello()
Say Hello()
Return
Return
Return
Return
TWO MARKS
1) Define Java Bean.
A Java Bean is a reusable software component that can be manipulated visually in a
builder tool.
The builder tools may include web page builders, GUI layout builders. Sometimes the
“builder tool” may simply be a document editor.
The configuration settings of a bean can be saved in persistence storage and restored
at later time.
A bean may register to receive events from other objects.
Auxiliary software provided to help a person configure a bean.
6) Define Applets.
A Java applet is a small application written in Java, and delivered to users in the form of
bytecode. The user launches the Java applet from a web page. The Java applet then executes
within a Java Virtual Machine (JVM) in a process separate from the web browser
itself, yet it can appear in a frame of the web page, in a new application window, or in Sun's
AppletViewer, a stand-alone tool for testing applets.
7) Define Servlets.
The Servlet is a Java programming languageclass used to extend the capabilities of a
server.AServlet is an object that receives a request and generates a response based on that
request.
9) What is EJB?
Enterprise Java Beans (EJB) technology is the server-side component architecture for the
Java 2 Platform, Enterprise Edition (J2EE) platform. Enterprise JavaBeans (EJB) is a
managed, server-side component architecture for modular construction of enterprise
applications.Enterprise JavaBeans (EJBs) are a part of the Java 2 Enterprise Edition
(J2EE) specifications. EJBs provide developers with a distributed, object-oriented,
component-based architecture.
JavaBeans are not typed EJBs are of three types - session beans and
entity beans and Message beans.
No explicit support exists for transactions EJB's may be transactional and the EJB
in javaBeans. servers provide transactional support