• •

Home Java
○ ○ ○ ○ ○ ○ ○ ○ ○ ○

Core Java Java SE 6 Advanced Java JSP Servlets JDBC EJB Web Services J2ME JSTL Hibernate Struts 1.x Struts 2 JSF JavaFX Ajax Spring 2.5 Spring 3

○ ○ ○ ○ ○ ○ ○ ○

○ ○ ○ ○ • ○ ○ • ○ ○ ○ ○ ○ ○ ○ • ○ ○ • ○ ○ ○ ○ ○ •

DOJO iBatis Flex 3 Flex 4 SQL MySQL GPS WiMaX VoIP WiFi HSDPA WAP EAI HTML Java Script DBUNIT ANT Maven JUNIT Jmeter Servers for Java Tomcat Apache Geronimo Jboss PHP Tutorial Starting PHP PHP MySQL Zend FrameWork



Web Development

Build/Test Tools

○ ○ ○ ○

○ ○ ○ ○

Home Ejb Application Server

Top of Form

partner-pub-0714 FORID:10


w w w .roseindia.n

Bottom of Form

Application Server Posted on: May 23, 2009 at 12:00 AM An application server is an application program that accepts connections in order to service requests, by sending back responses.

Application Server
An application server is an application program that accepts connections in order to service requests, by sending back responses. An application server can run remotely (connected to client through a computer network) or can exist on the same computer where the client application is running. Examples include file server, database server, backup server, print server, mail server, web server, FTP server, application server, VPN server, DHCP server, DNS server, WINS server, logon server, security server, domain controller, backup domain controller, proxy server, firewall, etc. Application server are developed to support the quick development of the enterprise applications. They provide security and state maintenance with the data base and persistence. An application server may be a part of a three tier architecture model. A three tier architecture includes the Client Tier, Middle Tier and the EIS (Enterprise Information System) Tier. It may consists of Presentation Tier (as the GUI interface), Middle Tier as the collection of business logic application and the EIS (Enterprise Information System). The view tier is nothing but the web based graphical user interface to interact with the clients, Middle tier is the combination of web containers and the EJB containers. EIS contains persistence and the database management systems to support the applications. JEE Platform requires database to store the business data. This database is accessible by means of JDBC, JDO or the SQLJ APIs. We can also access the database through enterprise beans, web components and the application client components.

nt. connected. etw. xi. connect. cli. s. pp. server. cat. ica. ie. remote. in. ca. running. th. is. client. same. ica. sam. me. run. li. through. app. put. s. net. where. st. e. pl. ati. em. k. net. to. s. application. sa. network. hr. computer. compute. exi. cl. work. sam. at. cte. o . com. on. can. rv. tw. om. io. m.Related Tags for Application Server: c. ap.

These are: 1. These services simplifies the development process of large and distributed applications and the developer just have to concentrate on solving the problem occurred in it. • • • Applications developed by using the enterprise beans deal with a variety of clients. It benefits the client to be thin because the client runs on the small devices. The client developer does not bother about the code that implements business logic or the logic to access the databases. Session bean: These types of beans directly interact with the client and contains business logic of the business application. Message driven bean: It works like a listener or a consumer for a particular messaging service such as Java Message API or JPA for short. Transaction is the mechanism of managing the concurrent access of shared objects. simply by writing few lines of code. numerous and thin. Benefits of enterprise beans: Enterprise beans are widely used for developing large and distributed applications. Managing the fast growing number of users requires distributed application components across multiple machines means that the application must be scalable. These applications involves large number of data accessing concurrently by many users. 2. EJB container provides the system-level services (like transaction management and security authorization) to the enterprise beans. maintaining session for the clients retrieving and holding data from the database and communicating with the server. The client developer can focus only on the representation style of the client as all the business logic of the application is contained in the enterprise beans. Types of enterprise beans: EJB 3. This means that the clients are thinner. Features of EJB 3. Enterprise beans are used to perform various types of task like interacting with the client. so that the client can locate the enterprise beans. Enterprise Beans Enterprise beans are the Java EE server side components that run inside the ejb container and encapsulates the business logic of an enterprise application. The client locating the enterprise bean may be various. Enterprise beans support transaction to ensure the integrity of the database.Enterprise beans are the Java EE server side components that run inside the ejb container and encapsulates the business logic of an enterprise application.0 .0 defines two types of enterprise beans. That means applications developed by using the enterprise components can run on any complaint J2EE server. Developing new applications from the existing beans is much easier because the enterprise beans are portable components. When to use the enterprise beans: Some of the points are illustrated below that signifies the use of enterprise beans. Enterprise applications are the software applications developed intended to use at large scale.

Whenever a MDB has an unexpected problem then the container logs the error and communicate it with the help of javax.rmi. when the bean does not receive the notification from the container about its life cycle's methods then the bean has to implement the component interfaces regardless whether it is needed or not.SessionBean or javax. Now the next question that arises is that how a bean class get notified by the container if it is interested? The solution is that there are two ways to do so.MessageDrivenBean in case of message driven bean. Annotations are the . The container used to call the appropriate method of the component interface to handle the bean's instance life cycle events according to the way it wants. Made use of java annotations. Business methods on remote interface can throw arbitrary application exceptions. While in case of EJB 2. the bean provider can implement a separate bean class that consists of all the callback notification methods that inform the container to treat it as a listener class. For example.0 that provides some simplification over the previous EJB API.EJBException to the corresponding resource adapter rather than the client.ejb.RemoteException.1 or in earlier versions are used to provide a way through which the container notifies the bean instances of various life cycles they are affecting it.rmi. Package javax.rmi. Elimination of Component Interface: Component interface in EJB2. These component interfaces includes the various life cycles methods implemented by the bean class. Consider the situation. system level problems.EJBException encapsulates exceptions such as protocols.0 that makes the EJB programming model simple and more efficient.ejb. Simplifies APIs to make flexible for bean's environment.RemoteException. Since EJBException is the subclass of the java. a bean provider can implement the notification method inside the bean class and designate this method to handle the corresponding events In both the cases bean class uses annotations. The bean provider designates the business interface as local business interface or the remote business interface or both according to the client whether it is local or remote. In case of session bean. There are various simplification made in EJB 3. the bean class does not need to implement the javax.0 like: • • • • No need of home and object interface.1 all the methods of home and object interface throws the java.ejb. A message driven bean does not need to include the business interface as there is no direct interaction of the client with the message driven bean.Now its time to look over the new features of EJB 3. Now we will discuss all the above aspects of EJB3. Bean class can close the JDBC database connection within the ejbDestroy() method to free up the resources.ejb. The second way is that. simply by invoking ejbDestroy() method on the corresponding class of the message driven bean. the first one is. while they are not allowed to throw java. the container notifies the message driven bean instance that it is about to destroy. The new session beans contain all the business methods inside the business interface. Similarly the container that is going to associate a client in case of stateful notifies the bean instance by calling the ejbCreate() method on the bean class and the bean class instantiates the bean instance.RemoteException therefore we did not include it in throws clause of business methods. The previous versions of the component interface are used to stay in the events in its lifecycle. Elimination of Home and Remote Interfaces: Deprecation of home and remote interfaces simplifies the development. No need of any component interface. or otherwise that the container returns to the client.

Annotations behaves like the meta. means you are free to add your code and can also apply them to variables.0 does not enforce to implement all unnecessary callback methods but can designate any other method to receive the notification for life cycle events. EJB 3. Simplified Access to Environment: Almost all the EJBs are required to access the environment to gain access to external resources. Enhanced Lifecycle Methods and Callback Listener Classes: EJB 3. To know about the annotation just click on the link annotations. We can also use the callback listener class instead of callback methods defined in the same bean class. We can also define an interceptor class instead of defining the interceptor methods in the bean class. Stateless session beans.ejb. The literal meaning of meta data is data about data. Dependency Injection: Dependency injection is the mechanism through which the container injects the requested environmental entry to make available to the bean instance before any bean instance is invoked on that particular instance. Bean must use the JNDI API to access the environmental dependencies. Stateful session beans and message driven beans may includes the interceptors.additional key features of EJB 3. fields type declarations. Simple JNDI lookup of EJB: Lookup of the EJB has been simplified so that the client can directly invoke methods on EJB rather than creating the bean instance simply by invoking create method on EJB. javax. To get hold of these entries EJB mainly relies on JNDI API. Another way through which a JNDI accesses the environment variables is the lookup() method of the EJBContext interface. Bean instances may use the dependency injection to access EJBContext instance. the container can not make available the environmental entries due to which the bean is functioning properly. Annotations are like meta data. Bean methods used for dependency injection should follow the java naming convention for properties in that they should follow the setXXX() convention. transaction context in which its method is invoked and so on.EJBContext API works like a window for the bean to the outside world through which it is interacting to the container. Then the container injects these entries into bean variables or methods. Annotations Sun Microsystem added the features like annotation to make the development easier and more efficient in jdk 5. in such situations the container discards the bean instances and creates new instances. Consider the situations like dependency injection fails due to some reasons. EJB Context: Bean must know about its environment at runtime such as security principle. EJBContext is further categorized into SessionContext and MessageDrivenContext for the session beans and message driven beans respectively. It is bean provider's duty to tell the container that which method or variables should be injected at runtime.0 specifications. The main objective to develop the annotations is to make the development easier. Interceptors: An intercept is a method used to intercept a business method invocation. The bean provider can do this by using the deployment descriptor or annotations. parameters. methods and . Java also signifies this meaning. enterprise beans and other entries like properties.0 also includes the features like lookup method on the EJBContest and dependency injection to access the bean's dependencies.

classes. Annotations provide a means of indicating about methods. You can also add the data within the parenthesis after the annotation name. dependencies. Fundamentals of annotations While going through the annotations you should consider two things. The first one is the "annotation" itself and second one is the "annotations types". Quoting from Sun's official site. Defining an annotation (Annotation type) public @interface Example { String showSomething(). marker annotations does not contain any elements except the name itself. • Marker: Like the marker interface." Annotation is the way of associating the program elements with the meta tags so that the compiler can extract program behavior to support the annotated elements to generate interdependent code when necessary. used to give some life to the code you are using. Lets illustrate the concept more clearly by using some examples. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it. The example given below clarifies the concept of marker interface. } Annotating the code (Annotation) Example (showSomething="Hi! How r you") public void anymethod() { . An annotation is the meta tag. While annotation type is used to define annotations so that you can use them while creating your own custom annotations. } Annotation Types: Three types of annotations types are there in java.. "It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. an annotation includes the "at" @ sign followed by the annotation type. Example: public @interface Example{ } Usage: @Example public void anymethod() { -----------} . XDoclet contains all these features and is widely used. incompleteness and also about the references on other methods and classes respectively. An annotation type definition appends an "at" @ sign at the start of the interface keyword with the annotation name..constructors. On the other hand.. Metadata is also used to create the documentation to perform rudimentary compile time checking and even for tracking down the dependencies in code.

Therefore use full value annotations to pass the values to all the data members. Method declaration should not contain any parameter. It means that these can be represented with the data and value pair or we can use the shortcut syntax (just by using the value only within the parenthesis). } Usage: @Example ("Hi ! How r you") public void anymethod(){ -------} • Multi-value or Full-value: These types of annotations can have multiple data members. } Usage: @Example (showSomething = "Hi! How r you". int num. name="zulfiqar" ) public void anymethod{ // code here } Rules defining the Annotation type: Here are some rules that one should follow while defining and using annotations types • • • • Start the annotation declaration starting with the symbol "at" @ following the interface keyword that should follow the annotation name. Method declaration should not throw any exception. num=5.• Single-value: This type of elements provide only single value. Example: public @interface Example{ String showSomething(). String name. Example: public @interface Example{ String showSomething(). Method using annotations should return a value. one of the types given below: • • • • • String primitive enum Class array of the above types Annotations: JDK 5 (Tiger) contains two types of annotations: .

The example given below illustrates this concept. } } Suppose there is spell mistake in the method name such as the name is changed from toString to toStrimg. Meta annotations: Also known as annotations of annotations are used to annotate the annotation-type declaration. Lets take an example and demonstrate what will happen if the annotated method does not override the method in the super class.println("Method has been depricated'"). Example 1: public class Override_method{ @Override public String toString(){ return super. Example: Lets first create the class containing the deprecated method.". Now will discuss in brief each of the above simple annotation types along with examples.java:24: method does not override a method from its superclass @Override 1 error BUILD FAILED (total time: 0 seconds) Deprecated annotation: These types of annotations ensure that the compiler warns you when you use the deprecated element of the program. • • • Override Depricated Suppresswarnings Simple annotations: JDK 5 includes three types of simple annotations. We can not use these types of annotations for creating the custom annotation type. Override annotation: The override annotation ensures that the annotated method is used to override the method in the super class.• • Simple annotations: These types of annotations are used to annotate the code only. .toString() + "Will generate an compile time error. JDK 5 (also known as Tiger) does not include many built-in annotations but it facilitates to core java to support annotation features. public class Deprecated_method{ @Deprecated public void showSomething() { System.out. If the method containing this type of annotation does not override the method in the super class then the compiler will generate a compile time error. Then on compiling the code will generate the message like this: Compiling 1 source file to D:tempNew Folder (2) TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctest myannotationTest_Override.

showSomething(). Note: Applying annotation at most deeply nested elements is a good idea.myannotation.showSomething(). On compiling the class Depricated_method does not generate any error. It is better to apply annotations at the method level rather than the class to annotate a particular method.Deprecated_method has been deprecated d. Lets take an example: Suppose you annotate a class to suppress a warning and one of its method to suppress another warning. } public Test_Deprication() { Deprecated_method d = new Deprecated_method(). } The method showSomething() in the above example is declared as the deprecated method. 1 warning The Suppresswarning annotation: These types of annotations ensure that the compiler will shield the warning message in the annotated elements and also in all of its sub-elements. } @SuppressWarnings({"deprecation"}) public void showSomething() { Deprecation_method d = new Deprecation_method().showSomething(). d. That means we can't further use this method any more. d. While compiling the class Test_Deprication generates the message like this: Compiling 1 source file to D:tempNew Folder (2)TestJavaApplication1buildclasses D:tempNew Folder (2)TestJavaApplication1srctestmyannotation Test_Deprication.java:27: warning: [deprecation] showSomething() in test. Lets demonstrate it by an example: public class Test_Depricated { public static void main(String arg[]) throws Exception { new TestDepricated().showSomething().} } Now lets try to invoke this method from inside the other class: public class Test_Deprication { public static void main(String arg[]) throws Exception { new Test_Deprication(). } } This example is suppressing the deprecation warnings that means we can't see the warnings any more. then both the warning will be suppressed at the method level only. .

} } The @Target(ElementType.doTestElement().printf("Testing Target Element annotation").out. Lets try to apply this type of annotation to annotate an element: public class Test_Annotations { @Test_Target(doTestElement="Hi! How r you") private String str. Here is the listing of the elements of the enumerated types as its value: • • • • • • • @Target(ElementType. @Target(ElementType. @Target(ElementType. } @Test_Target(doTestElement="Hi ! How r you") public void doTestElement() { System.Meta-Annotations (Annotation Types): There are four types ofm Meta annotations (or annotations of annotations) defined by the JDK 5. } Now lets create a class that use the Test_Element annotation: public class Test_Annotations { public static void main(String arg[]) { new Test_Annotations().ANNOTATION_TYPE)?specifies that the declared type itself is an annotation type. public static void main(String arg[]) { new Test_Annotations().doTestElement(). @Target(ElementType.FIELD)?applicable to field or property.METHOD) public @interface Test_Element { public String doTestElement().CONSTRUCTOR)?applicable to constructors.METHOD) specifies that this type of annotation can be applied only at method level. These are as follows: • • • • Target Retention Documented Inherited Target annotation: Target annotation specifies the elements of a class to which annotation is to be applied.PARAMETER)?applicable to the parameters of a method. @Target(ElementType.METHOD)?applicable to method level annotation.LOCAL_VARIABLE)?applicable to local variables. Compiling and running the above program will work properly. } . @Target(ElementType. @Target(ElementType. Here is an example that demonstrates the target annotation: Example: @Target(ElementType.TYPE)?applicable to any element of a class.

Lets demonstrate that how this type of annotations are applied by taking an example using RetentionPolicy. RetentionPolicy.METHOD) at the field level by declaring the element private String str. after the @Test_Target(doTestElement="Hi ! How r you") statement. On compiling this code will generate an error like this: "Test_Annotations. • • • RetentionPolicy. Example: @Documented public @interface Documented_Demo { String doTestDocumentedDemo().CLASS: This type of annotation will be retained at the compile time the virtual machine (VM) will ignore them.RUNTIME) that indicates the VM will retained your Retention_Demo annotation so that it can be read effectively at runtime. } This example uses the annotation type @Retention(RetentionPolicy. There are three type of Retention annotations are of three types.java": D:R_AND_DTest_Annotationsrctestmyannotation Test_Annotations. . } } Here we are trying to apply @Target(ElementType.RUNTIME.printf("Testing Target Element annotation").SOURCE: This type of annotation will be retained only at source level and the compiler will ignore them.public void doTestElement() { System. Example: @Retention(RetentionPolicy.out.RUNTIME) public @interface Retention_Demo { String doRetentionDemo(). column 0 @Test_Target(doTestElement="Hi ! How r you") ^ Error in javac compilation Retention annotation: These types of annotation specify where and how long annotation with this types are to be retained. javadoc does not include the annotation by default. The given example demonstrates the use of the @Documented annotations.RUNTIME: Virtual machine will retained the annotation of this type and they can be read only at run-time. In this type of annotation all the processing is done by javadoc-like tool. Include the annotation type information by using @Documented in the generated document.java:16: annotation type not applicable to this kind of declaration at line 16. RetentionPolicy. Documented annotation: This type of annotation should be documented by the javadoc tool.

out.doTestRetentionDemo(). annotate the class with our annotation: @ParentObjectDemo public Class ChildObjectDemo { } The above example shows that you do not need to define the interface methods inside the implemented class. make changes in Test_Annotations class as follows: public class Test_Annotations { public static void main(String arg[]) { new Test_Annotations().printf("Testing 'Documented' annotation"). } Now. } @Retention_Demo (doTestRetentionDemo="Hello retention annotation") public void doTestRetentionDemo() { System. Lets demonstrate the benefits of using the @Inherited tag by an example: Example: Lets first.printf("Testing 'Retention' annotation"). define the annotation: @Inherited public @interface ParentObjectDemo { boolean isInherited() default true. The @Inherited tag automatically inherits the methods for you. If you specify @Inherited tag before defining a class then apply the annotation at your class and finally extend the class then the child class inherits the properties of the parent class automatically. .doTestDocumentedDemo(). } public String showSomething() { return "". } } Inherited Annotation: This annotation is little bit complex. Suppose you define the implementing class in the old-fashioned-java-style then let us see the effect of doing this: public class ChildObjectDemo implements ParentObjectDemo { public boolean isInherited() { return false. } @Documented_Demo (doTestDocumentedDemo="Hello Test documentation") public void doTestDocumentedDemo() { System.out. It inherits the annotated class automatically. String showSomething() default "Show anything?".} Next. new Test_Annotations().

whenever a client wants to perform any of these actions such as making a reservation or validating a credit card. . The session bean decides what data is to be modified. and work flows. For example. A session bean makes an interactive session only for a single client and shields that client from complexities just by executing the business task on server side.annotation.Annotation class. } public Class annotationType() { return null. } public int hashCode() { return 0. As long as the client terminates. the session bean uses an entity bean to access or modify data. } } Have you seen the difference? You have to implement all the methods of the parent interface. The EJB container may destroy a session bean if its client times out. You will also have to include all these methods in your class regardless of whether you are implementing all these methods or not. session bean associated with this client is also terminated and the data associated with this bean is also destroyed. a session bean should be used. Session Beans What is a Session bean A session bean is the enterprise bean that directly interact with the user and contains the business logic of the enterprise application.} public boolean equals(Object obj) { return false. A session bean is the enterprise bean that directly interact with the user and contains the business logic of the enterprise application.lang. A session bean can neither be shared nor can persist (means its value can not be saved to the database) its value. Typically. A session bean can have only one client. } public String toString() { return "". You will have to implement the equals(). business rules. They implement business logic. A session bean represents a single client accessing the enterprise application deployed on the server by invoking its method. and the hashCode() methods of the Object class and also the annotation type method of the java. algorithms. An application may contain multiple sessions depending upon the number of users accessing to the application. toString(). Session beans are relatively short-lived components.

e. So they do not persist data across method invocation and therefore there is no need to passivates the bean's instance. A stateful session bean retains its state across multiple method invocations made by the same client. the session ends and the state disappears. the EJB container destroys a stateless session bean.The above figure shows how Session Bean interacts with the clients as well as with the Entity Beans. Because the client interacts with its bean. this state is often called the conversational state. If the stateful session bean's state is changed during a method invocation. Once the method is finished. the client-specific state should not be retained i. Once the client removes the bean or terminates. When a client invokes the methods of a stateless bean. they provide the better scalability for applications that require large numbers of clients. Stateful Session Beans: These types of beans use the instance variables that allows the data persistent across method invocation because the instance variables allow persistence of data across method invocation. the instance of bean variables may contain a state specific to that client only for the duration of a method invocation. These types of session beans do not use the class variables (instance variables). Session beans are divided into two parts. The client sets the data to these variables which he wants to persist. Because stateless session beans can support multiple clients. then that state will be available to the same client on the following invocation. • Stateless Session Beans: A stateless session bean does not maintain a conversational state with the client. The state of a client bean is retained for the duration of the client-bean session. • .

When to use session beans: Generally session beans are used in the following circumstances: • • • • • • • • When there is only one client is accessing the beans instance at a given time. The bean is implementing the web services. When the bean works as the mediator between the client and the other component of the application. consider a customer using a debit card at an ATM machine. The above figure demonstrates how the Stateless Session Beans are created and destroyed. The user interface calls methods of session beans if the user wants to use the functionality of the session bean. transferring funds. . What the bean wants to holds information about the client across method invocation.For example. or making a withdrawal. So the bean needs to keep track its state for each of these operations to the same client. These operations could be performed one by one. When the bean have to manage the work flow of several other enterprise beans. Thus Stateful session beans has the extra overhead for the server to maintain the state than the stateless session bean. If there is only one method invocation among all the clients to perform the generic task. For this. by the same customer. Whether it does not exist or ready for method invocation. the container performs the dependency injection before invoking the annotated @PreConstruct method if any exists. A stateless session bean starts its life cycle when the client first obtains the reference of the session bean. The ATM could perform various operations like checking an account balance. After invoking the annotated @PreConstruct method the bean will be ready to invoke its method by the client. Stateful session beans are useful in the following circumstances: Stateless session beans are appropriate in the circumstances illustrated below: Life Cycle of a Stateless Session Bean: Since the Stateless session bean does not passivates across method calls therefore a stateless session bean includes only two stages. Session beans can call to other session beans and entity beans. If the bean does not contain the data for a specific client. When the bean is not persistent that means the bean is going to exist no longer.

Stateless Session Bean Example In this part of Enterprise Session Beans. the client calls the annotated @Remove method after this the container calls the annotated @PreDestroy method which results in the bean to be ready for the garbage collection. which performs the calculations.The container calls the annotated @PreDestroy method while ending the life cycle of the session bean. and two types of clients: an application client and a web client. The container may deactivate a bean while in ready state (Generally the container uses the least recently use algorithm to passivates a bean). Life Cycle of a Stateful Session Bean: A Stateful session bean starts its life cycle when the client first gets the reference of a stateful session bean. The container invokes the annotated @PrePassivate method before passivating the bean. the bean is ready for garbage collection. The example application consists of an enterprise bean. . and run a simple Java EE application named example using stateless session bean. Multiplication. After this. In the passivate mechanism the bean moves from memory to secondary memory. The purpose of example is to performs the mathematical operations such as Addition. The above image shows the various states of the Stateful Session Beans While ending the life cycle of the bean. Subtraction. If a client invokes a business method on the passivated bean then the container invokes the annotated @PostActivate method to let come the bean in the ready state. and Division. you will learn how to develop. Before invoking the method annotated @PostConstruct the container performs any dependency injection after this the bean is ready. deploy.

Create the web client: WebClient 3. (i) Coding the Business Interface The business interface defines the business methods that a client can call remotely. import javax.annotation. package net. import java. float y).ejb.*. multiply. Create the enterprise bean: CalculatorBean 2.math.Remote.ejb3. public float multiply(float x. import javax.*. public float subtract(float x. run the web client.stateless. float y). This class implements the four business methods (add. The source code for the CalculatorRemote business interface is given below.There are following steps that you have to follow to develop a example JEE application. II. I. Creating the enterprise bean: The enterprise bean in our example is a stateless session bean called CalculatorBean.Remote. 4. package net. float y).roseindia.lang.ejb. The source code for CalculatorBean is in ?net/roseindia/ejb3/stateless? directory. The business methods are implemented in the enterprise bean class.class) public class CalculatorBean implements CalculatorRemote{ . @Remote public interface CalculatorRemote { public float add(float x.*.ejb3. import javax. Creating CalculatorBean requires these steps: (i) Coding the bean?s Remote business interface and Enterprise bean class. public float division(float x. 1. (ii) Compiling the source code with the Ant tool. } Note that.roseindia. float y). subtract. division) that are defined in the CalculatorRemote business interface. the @Remote annotation decorating the interface definition.stateless.Stateless.ejb. The source code for the CalculatorBean class is given below. @Stateless(name="CalculatorBean") @Remote(CalculatorRemote. Using a browser. Deploy example onto the server.math. import java. This lets the container know that CalculatorBean will be accessed by remote clients. import java. Coding the Enterprise Bean Class The enterprise bean class for this example is called CalculatorBean.

Compiling and Packaging the example Example Now you are ready to compile the remote business interface (CalculatorRemote. The source code for the ?form.java) and the application client (CalculatorClient. This lets the container know that CalculatorBean is a stateless session bean.jsp? is given below. A JSP page is a text-based document that contains JSP elements. then package the compiled classes into an enterprise bean JAR.public float add(float x. expressed in any text-based format such as HTML. float y){ return x * y. the enterprise bean class (CalculatorBean. and static template data. WML. the @Stateless annotation decorating the enterprise bean class. } public float division(float x. } public float multiply(float x. Creating the calculator Web Client The web client is contained in the JSP page "WebClient. float y){ return x + y. which construct dynamic content. float y){ return x . float y){ return x / y. } public float subtract(float x.jsp".java). II.java).y. <html> <head> <title>Calculator</title> </head> <body bgcolor="pink"> <h1>Calculator</h1> <hr> <form action="WebClient. } } Note that. and XML.jsp" method="POST"> <p>Enter first value: <input type="text" name="num1" size="25"></p> <br> <p>Enter second value: <input type="text" name="num2" size="25"></p> <br> .

*. of the JSP page. A scriptlet (enclosed within the <% %> characters) retrieves the parameters from the request and converts it to a Float object. charset=UTF-8" %> <%@ page import="com. and JSP expressions (enclosed within the <%= %> characters) insert the results into the stream of data returned to the client. this code appears in a JSP declaration (enclosed within the <%! %> characters) that contains the initialization method. a JSP scriptlet invokes the enterprise bean?s business methods.stateless.lookup("example/CalculatorBea n/remote"). <%@ page contentType="text/html.ejb3.jsp? are used for locating the business interface. InitialContext ic = new InitialContext(). CalculatorRemote calculator = (CalculatorRemote)ic. The classes needed by the client are declared using a JSP page directive (enclosed within the <%@ %> characters).javajazzup.naming.<b>Seclect your choice:</b><br> <input type="radio" name="group1" value ="add">Addition<br> <input type="radio" name="group1" value ="sub">Subtraction<br> <input type="radio" name="group1" value ="multi">Multiplication<br> <input type="radio" name="group1" value ="div">Division<br> <p> <input type="submit" value="Submit"> <input type="reset" value="Reset"></p> </form> </body> </html> The following statements given below in ?WebClient.*"%> <%! private CalculatorRemote calculator = null. Finally. and invoking a business method. The full source code for the WebClient program is given below. javax. creating an enterprise bean instance. public void jspInit() { try { InitialContext ic = new InitialContext(). Because locating the business interface and creating the enterprise bean are performed only once.examples. float result=0. jspInit. .

floatValue().num2.num2. } .equals("add")) result=calculator. if(s3.out.num2.getParameter("num2").floatValue(). } } public void jspDestroy() { calculator = null.println("Loaded Calculator Bean"). //result = "Not valid".getParameter("num1"). else if(s3.getParameter("group1"). String s3 = request.equals("multi")) result=calculator. if ( s1 != null && s2 != null ) { Float num1 = new Float(s1).floatValue()).calculator = (CalculatorRemote) ic.floatValue()). System.floatValue()).equals("sub")) result=calculator.subtract(num1.printStackTrace (). else result=calculator.lookup("example/CalculatorBean/remot e").out. } %> <% try { String s1 = request.getMessage()). System.floatValue().floatValue(). //CalculatorBean } catch (Exception ex) { System. %> <p> <b>The result is:</b> <%= result %> <p> <% } }// end of try catch (Exception e) { e.division(num1.floatValue()). String s2 = request.out.println("Error:"+ ex.num2. Float num2 = new Float(s2).add(num1.println(s3).multiply(num1. else if(s3.

you would have to compile it. build.7."> <target name="init"> <!-. Deploy example onto the server To deploy the created example application we are going to use Jboss 4.0 Tutorial</b></font> Click <a href="ejb3/form. If the web client were a servlet.xml files.base" value="${basedir}"/> <property name="classdir" value="$ {dirs.jsp">Calculator Example</a> to execute Calculator<br></p> </body> </html> III.base}/src"/> <property name="web" value="${dirs. <%@page language="java" %> <html> <head> <title>Ejb3 Stateless Tutorial</title> </head> <body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.2.base}/build/classes"/> <property name="src" value="${dirs.0 Application Server about which you have read in the previous section of this Javajazzup issue.0 JBoss 4. So you first need to download the following tools to deploy this application. • • • (i) JDK 1.5 or Higher apache-ant-1.2.Define --> <property name="dirs.xml <?xml version="1.base}/web"/> <property name="deploymentdescription" value="$ .0 Make a directory structure. The source code for the ?index.%> Note: The Application Server automatically compiles web clients that are JSP pages.0"?> <project name="Jboss Tutorials" default="all" basedir=".2. You can Click here to extract the readymade directory structure according to this tutorial. Do the following steps to deploy the example application: (ii) Create the essential deployment descriptor .jsp? is given below that will actual call the client-design form.

jar"/> <pathelement path ="$ </path> <!-.base}/deploymentdescriptors"/> <property name="warFile" value="example.base}/build/ear"/> <property name="warDir" value="${dirs.buildEar"/> <!-.class" /> </copy> <copy todir="${warDir}/WEB-INF"> <fileset dir="${deploymentdescription}/web/" includes="web.buildJar.xml" /> </copy> <copy todir="${warDir}"> .ear"/> <property name="jarFile" value="example.classpath"/> </javac> </target> <!-.Compile Java Files and store in /build/src directory --> <target name="build" > <javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.classpath for Project --> <path id="library.jar"/> <pathelement path ="libext/ejb3persistence.{dirs.jar"/> <property name="earDir" value="$ {dirs.Create Meta-inf and classes directories --> <mkdir dir="${earDir}/META-INF"/> <mkdir dir="${jarDir}/META-INF"/> <mkdir dir="${classdir}"/> </target> <!-.base}/build/jar"/> <!-.build.Create the web archive File --> <target name="buildWar" depends="init"> <copy todir="${warDir}/WEB-INF/classes"> <fileset dir="${classdir}" includes="**/*.base}/build/war"/> <property name="jarDir" value="${dirs.buildWar.classpath"> <pathelement path ="libext/servletapi.war"/> <property name="earFile" value="example.Main target --> <target name="all" depends="init.jar"/> {classpath}"/> <pathelement path ="libext/javaee.Create Web-inf and classes directories --> <mkdir dir="${warDir}/WEB-INF"/> <mkdir dir="${warDir}/WEB-INF/classes"/> <!-.java" > <classpath refid="library.

/${earFile}" basedir="${earDir}" /> <copy todir="C:/jboss-4.xsd"> <display-name>Stateless Session Bean Example</display-name> <module> .com/xml/ns/javaee/application_5. Application.xml.weblogicejb-jar..sun.Create war file and place in ear directory --> <jar jarfile="${earDir}/${warFile}" basedir="${warDir}" /> </target> <!-.weblogic-cmp-rdbms-jar.w3.Create ear file and place in ear directory --> <jar jarfile=".com/xml/ns/javaee" xmlns:xsi="http://www.sun.<fileset dir="${web}" includes="**/*.GA/server/default/deploy/"> <fileset dir=".0" encoding="UTF-8"?> <application xmlns="http://java.org/2001/XMLSchema-instance" version="5" xsi:schemaLocation="http://java.*" /> </copy> <!-./" includes="${earFile}" /> </copy> </target> </project> Put this file in the base (stateless\code)directory.class" /> </copy> <copy todir="${jarDir}/META-INF"> <fileset dir="${deploymentdescription}/jar/" includes="ejb-jar.sun.xml.xml" /> </copy> <!-.com/xml/ns/javaee http://java.0.xml" /> </copy> <!-.xml <?xml version="1..Create the ear File --> <target name="buildEar" depends="init"> <copy todir="${earDir}/META-INF"> <fileset dir="${deploymentdescription}/ear" includes="application.Create the jar File --> <target name="buildJar" depends="init"> <copy todir="${jarDir}"> <fileset dir="${classdir}" includes="**/*.2.Create jar file and place in ear directory --> <jar jarfile="${earDir}/${jarFile}" basedir="${jarDir}" /> </target> <!-.

Inc. Put all . and go to the Stateless\code directory.jar</ejb> </module> </application> Put this file in the Stateless\code\deploymentdescriptors\ear directory.3//EN" "http://java.com/dtd/webapp_2_3.xml <?xml version="1.sun.2.ear file to the jboss-4. web.war</web-uri> <context-root>/example</context-root> </web> </module> <module> <ejb>example.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems. (iii) Start command prompt.GA\server\default\deploy directory. Then type the command as: C:\Stateless\code>ant build.java files in the Stateless\code\src directory. Put all . V.0.//DTD Web Application 2.xml The Ant tool will deploy the example. Running the example Web Client Open the web browser and type the following URL to run the application: http://localhost:8080/example .jsp files in the Stateless\code\web directory.<web> <web-uri>example.dtd"> <web-app > </web-app> Put this file in the Stateless\code\deploymentdescriptors\web directory.

Click at the given link as Calculator Example: .

1. you will learn how to develop. you will learn how to develop. To manage account. I.0 In this part of Enterprise Session Beans. deploy. The account application consists of an enterprise bean. Create the enterprise bean: AccountBean 2. Create the application client: AccountCustomer 3. 4. Deploy account onto the server. The account session bean represents an account information in an online customer account. deploy. The bean?s customer can deposit to or withdraw the amount from his account. which performs the transactions. Creating the enterprise bean: The enterprise bean in our example is a statelful session bean called AccountBean. The purpose of account is to performs two transaction operations (deposit and withdraw) for the customer. and run a simple Java EE application named account using stateful session bean. Run the application client. The result is: 9. and run a simple Java EE application named account using stateful session bean. here are following steps that you have to follow to develop a account JEE application.Give values to the textbox and choose the desire option button as Addition then clicks the Submit button to get the result. you need the following code: • • Remote business interface (Account) Session bean class (AccountBean) The Business Interface: . and two types of clients: an application client and a web client. Stateful Session Bean Example In this part of Enterprise Session Beans.

import import import import javax.ejb. @Stateful(name="AccountBean") @Remote(AccountRemote. If the bean class implements a single interface. The source code for the Account business interface is given below.stateful. package ejbExample. The bean class may also implement more than one interface. } public float withdraw(float amount){ balance -= amount. javax.Remote annotation.stateful.ejb. The AccountBean class must meet these requirements: • • The class is annotated @Stateful. } Coding the Session Bean Class: The session bean class for this example is called AccountBean.ejb.class) public class AccountBean implements AccountRemote { float balance = 0. @Remove public void remove().Stateful.*.ejb. The source code for the AccountBean class is given below.The Account business interface is a plain Java interface that defines all the business methods implemented in the bean class. The class implements the business methods defined in the business interface.Remote. the business interfaces must be specified by decorating the bean class with @Local or @Remote. If the bean class implements more than one interface. import javax.ejb. public float withdraw(float amount).Remove. public float deposit(float amount){ balance += amount. that interface is assumed to the business interface. javax. javax. @Remote public interface Account { public float deposit(float amount).Remote. The business interface is a local interface unless it is annotated with the javax. package ejbExample. This class implements the two business methods (deposit and withdraw). return balance.ejb. .

the remove method is a @Remove method shown as: @Remove public void remove() { balance = 0. we can retain the bean's state invoked by the client until we call the annotated @Remove method. In AccountBean .PrePassivate Life-cycle callback methods must return void and have no parameters. Thus.ejb. The container will remove the enterprise bean after a @Remove method completes.annotation. Implement optional business method annotated @Remote.PostConstruct javax.Remove in the stateful session bean class can be invoked by enterprise bean client to remove the bean instance. } } The Remove Method Business methods annotated with javax. and @PrePassivate. @PreDestroyInvoked.PostActivate javax. @PreDestroy. when the bean is about to be destoryed by EJB container before removing . Lets understands these callback annotated methods shown in the table given below: Method Description Invoked by the container on newly constructed bean instances before the first @PostConstr business method is invoked on the enterprise uct bean and after all dependency injection has completed. } @Remove public void remove() { balance = 0. @PostActivate.PreDestroy javax.ejb.ejb. annotated @PostConstruct.annotation. Life-Cycle Callback Methods: Methods in the bean class may be declared as a life-cycle callback method by annotating the method with the following annotations: • • • • javax.return balance. either normally or abnormally. } Stateful session beans also may: • • Implement any optional life cycle callback methods.

i. account = (AccountRemote) ic.getMessage()). } %> <% try { .println("Loaded Account Bean").examples. Invoked by the container after the container @PostActiva moves the bean from secondary storage to te active status.stateful.ejb3. } } public void jspDestroy() { account = null. System.*"%> <%! public AccountRemote account = null. float bal=0. the @PrePassiva container temporarily removes the bean from te the environment and saves it to secondary storage. } catch (Exception ex) { System.jsp file That illustrates the basic tasks performed by the client of an enterprise bean: • • Creating an enterprise bean instance Invoking a business method The full source code for the WebClient. public void jspInit() { try { InitialContext ic = new InitialContext(). Coding the account Web Client The application client source code is in the WebClient. javax.jsp program is given below.println("Error:"+ ex. <%@page language="java" %> <%@ page contentType="text/html. charset=UTF-8" %> <%@ page import="com.javajazzup.*.out.e.the enterprise bean instance and after any method annotated @Remove has completed. II. Invoked by the container before the container passivates the enterprise bean.lookup("example/AccountBean/remote").out.naming.

deposit(amt.withdraw(amt. else if(s2.getParameter("amt"). if(s2. } %> The source code for the ?form.getParameter("group1"). else %> <p>Please select your choice</p> <% } else %> <br>Please enter the amount<br> <p> The Transaction is complete<br> <b>Your Current Balance is:</b> <%= bal%> <p> <% }// end of try catch (Exception e) { e.floatValue()).jsp? is given below.equals("dep")) bal=account.equals("with")) bal=account. String s2 = request.String s1 = request.floatValue()).printStackTrace ().jsp" method="POST"> <tr><td></tr></td> <tr><td>Enter the amount in rupees: . if ( s1 != null) { Float amt = new Float(s1). <html> <head> <title>Bank Account</title> </head> <body> <h1><p align="center"><font size="6" color="#800000">Bank Transaction Request Form</h1> <hr><br> <table bgcolor="#FFFFCC" align="center"> <form action="WebClient.

jsp">Bank Transaction Example</a> to execute Bank Bean<br></p> </body> </html> III.jsp? is given below that will actual call the client-design form.<input type="text" name="amt" size="10"></tr></td> <br> <tr><td><b>Select your choice:</b></tr></td> <tr><td><input type="radio" name="group1" value ="dep">Deposit</tr></td> <tr><td><input type="radio" name="group1" value ="with">Withdraw<br></tr></td> <tr><td> <input type="submit" value="Transmit"> <input type="reset" value="Reset"></tr></td> <tr><td></tr></td> </form> </table> </body> </html> The source code for the ?index. Running the account Application Client .2.0 Tutorial</b></font> Click <a href="ejb3/form. Deploy account onto the server IV. <%@page language="java" %> <html> <head> <title>Ejb3 Stateful Tutorial</title> </head> <body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.