CHAPTER 2 ■■■ EJB Session Beans This chapter will discuss EJB session beans,the core business service objects used by EJB client applications.You'll gain an understanding of the simplified EJB session bean model with insights into the following topics: Types of session beans-stateful,stateless,and singleton-and when to use each one The bean class,business interfaces,and business methods Asynchronous methods ·Callback methods ·Interceptors ·Exception handling ·Client view Dependency injection with annotations related to session beans ·Timer service Introduction to Session Beans Session beans are Java components that run either in stand-alone EJB containers or in EJB containers that are part of standard Java Platform,Enterprise Edition(Java EE)application servers.These Java components are typically used to model a particular user task or use case,such as entering customer information or implementing a process that maintains a conversation state with a client application.Session beans can hold the business logic for many types of applications, such as human resources,order entry,and expense reporting applications.The EJB container provides services to the session bean,and the bean indicates which services it needs using Java annotations and/or XML metadata. Types of Session Beans Session beans are of three types: .Stateless:This type of bean does not maintain any conversational state on behalf ofa client application .Stateful:This type of bean maintains a state,and a particular instance of the bean is associated with a specific client request.Stateful beans can be seen as extensions to client programs, which are running on the server. Singleton:This type of bean is instantiated only once per application.Singleton beans live for the full duration of the application and maintain their state between client invocations. We will drill down into more specifics of stateless,stateful,and singleton beans in the following sections. 25
25 Chapter 2 EJB Session Beans This chapter will discuss EJB session beans, the core business service objects used by EJB client applications. You’ll gain an understanding of the simplified EJB session bean model with insights into the following topics: • Types of session beans—stateful, stateless, and singleton—and when to use each one • The bean class, business interfaces, and business methods • Asynchronous methods • Callback methods • Interceptors • Exception handling • Client view • Dependency injection with annotations related to session beans • Timer service Introduction to Session Beans Session beans are Java components that run either in stand-alone EJB containers or in EJB containers that are part of standard Java Platform, Enterprise Edition (Java EE) application servers. These Java components are typically used to model a particular user task or use case, such as entering customer information or implementing a process that maintains a conversation state with a client application. Session beans can hold the business logic for many types of applications, such as human resources, order entry, and expense reporting applications. The EJB container provides services to the session bean, and the bean indicates which services it needs using Java annotations and/or XML metadata. Types of Session Beans Session beans are of three types: • Stateless: This type of bean does not maintain any conversational state on behalf of a client application. • Stateful: This type of bean maintains a state, and a particular instance of the bean is associated with a specific client request. Stateful beans can be seen as extensions to client programs, which are running on the server. • Singleton: This type of bean is instantiated only once per application. Singleton beans live for the full duration of the application and maintain their state between client invocations. We will drill down into more specifics of stateless, stateful, and singleton beans in the following sections
CHAPTER 2 EJB SESSION BEANS When Do You Use Session Beans? Session beans are used to write business logic,maintain a conversation state for the client,and model back-end processes or user tasks that perform one or more business operations.Typical examples include the following: Asession bean in a human resources application that creates a new employee and assigns the employee to a particular department 。 A session bean in an expense reporting application that creates a new expense report Asession bean in an order entry application that creates a new order for a particular customer Asession bean that manages the contents of a shopping cart in an e-commerce application A session bean that leverages transaction services in an EJB container(removing the need for an application developer to write the transaction support) Asession bean used to address deployment requirements when the client applications are not collocated on the same server 。 Asession bean that le 。 Asession bean that impleme nts logging functionality and is shared between different components of an application Session beans can be or n ditional2- r or 3-tie tectur on /rich clie e applic y n profess ca binations.In the next section,we w ill investigate some of the possible com 3-Tier Architecture with Rich Client re-1shows a typical architecture for a session with a rich client fro ond o application that has sed by ch a ntat g techn ith t cts(POJOs),which are nin fro the co mand line.Ger nerally,the end user launches the client application from his or her desktop,enters some data,and triggers an event by pressing some user interface component,such as a Submit button.The general workflow may look something like this: 1.User action establishes a connection to the session bean running in the EJB container using remote method invocation(RMI). 2.The client application invokes one or more business methods in the session bean. 3.The session bean processes the request and validates data by interacting with databases, enterprise applications,legacy systems,and so on to perform a certain business operation or task. 4.Finally,the session bean sends a response back to the client application,either through data collections or simple objects that contain acknowledgment messages. 9
Chapter 2 ■ EJB Session Beans 26 When Do You Use Session Beans? Session beans are used to write business logic, maintain a conversation state for the client, and model back-end processes or user tasks that perform one or more business operations. Typical examples include the following: • A session bean in a human resources application that creates a new employee and assigns the employee to a particular department • A session bean in an expense reporting application that creates a new expense report • A session bean in an order entry application that creates a new order for a particular customer • A session bean that manages the contents of a shopping cart in an e-commerce application • A session bean that leverages transaction services in an EJB container (removing the need for an application developer to write the transaction support) • A session bean used to address deployment requirements when the client applications are not collocated on the same server • A session bean that leverages the security support provided by the container on the component or method level • A session bean that implements logging functionality and is shared between different components of an application Session beans can be used in traditional 2-tier or 3-tier architectures with professional/rich client applications, or in 3-tier web-based applications. These applications can be deployed in different logical and physical tier combinations. In the next section, we will investigate some of the possible combinations. 3-Tier Architecture with Rich Client Figure 2-1 shows a typical architecture for a session bean in 3 tiers with a rich client front-end application that has some data entry screens used by end users, such as customer service representatives, bank tellers, and so on. These client applications can be developed using Java Swing technology with the Java Platform, Standard Edition (Java SE), or they can be plain old Java objects (POJOs), which are run from the command line. Generally, the end user launches the client application from his or her desktop, enters some data, and triggers an event by pressing some user interface component, such as a Submit button. The general workflow may look something like this: 1. User action establishes a connection to the session bean running in the EJB container using remote method invocation (RMI). 2. The client application invokes one or more business methods in the session bean. 3. The session bean processes the request and validates data by interacting with databases, enterprise applications, legacy systems, and so on to perform a certain business operation or task. 4. Finally, the session bean sends a response back to the client application, either through data collections or simple objects that contain acknowledgment messages
CHAPTER 2 EJB SESSION BEANS EJB Container Professional Session Bean RMI Client JDBC Network Network Database Application Session Bean Session Bean Figure 2-1.Session beans in a3-tier architecture with a Rich Client 3-Tier Architecture for a Web Application This architecture,as shown in Figure 2-2,is typically front-ended by a weban g in the browser of a device renders the user interface(data entry scr ns,submit buttons,and so on)using web technologies such as lavaServer Pages (ISP).JavaServer Faces (ISF).or lava Servlets.Typical user actions.such as entering search criteria or adding certain items to the web application shopping cart,will invoke/call session beans running in an EJB container via one of the aforementioned web technologies.Once the session bean gets invoked,it processes the request and sends a response back to the web application,which formats the response as required and then sends the response on to the requesting client device(browser,smart phone,telnet,and so forth). WebApplications Web Container EJB Container Browser Network JSP Session Bean Network Local JDBC JSF Remote Session Bean Network Database ←Network Servlet Session Bean Figure 2-2.Session beans in a 3-tier architecture with a web application In the 3-tier tecture just discussed,the clien app lication (which is the app olication)and the session bean me machine.The ey can also be run on ph te machines that ha 27
Chapter 2 ■ EJB Session Beans 27 3-Tier Architecture for a Web Application This architecture, as shown in Figure 2-2, is typically front-ended by a web application running in the browser of a desktop or laptop computer. These days, other types of client devices, such as smart phones, tablets, cell phones, and telnet devices, are also being used to run these applications. The web application running in a browser or mobile device renders the user interface (data entry screens, submit buttons, and so on) using web technologies such as JavaServer Pages (JSP), JavaServer Faces (JSF), or Java Servlets. Typical user actions, such as entering search criteria or adding certain items to the web application shopping cart, will invoke/call session beans running in an EJB container via one of the aforementioned web technologies. Once the session bean gets invoked, it processes the request and sends a response back to the web application, which formats the response as required and then sends the response on to the requesting client device (browser, smart phone, telnet, and so forth). Figure 2-1. Session beans in a 3-tier architecture with a Rich Client In the 3-tier architecture just discussed, the client application (which is the web application) and the session beans can be run within the same instance of an application server (collocated) or from different instances running on the same machine. They can also be run on physically-separate machines that have an instance of an application server. Figure 2-2. Session beans in a 3-tier architecture with a web application
CHAPTER 2 EJB SESSION BEANS Stateless Session Beans Stateless session beans are comprised of the following elements: Abean class,which contains the business method implementation to be executed Optionally,o eorebusnessnallnifferfebean's business methods to be presented toclient applications The Bean Class A stateless session bean class is any standard Java class that has aclass-level annotation ofstateless.If deployment ons,then the be e de If the e @sta ther cl a If hoth ar 、gs or value o the ot des or will Note Starting with EJB 3.1,a session bean class can be a sub-class of another session bean class rate the use of statel s sessio eans,we SearchFacade sion bean that provides various search facilities to client applications regarding available wines.The workflow is as follows: 1. Users of the a pplication will type in or choose one or more search criteria,which will b ed to the SearchFacad e session bean 2 y he nt the SearchFacade bean the backend database. 3.The bean returns to the client applications the information that satisfied the search criteria. listing 2-1 shows the definition of the searchFacade bean.in the following sections of this chapter.we will build the code that will show the preceding workflow in action.SearchFacadeBean is a standard Java class with a class-level annotation of@Stateless. Listing2-1.SearchFacadeBean.java package com.apress.ejb.chapter02; import javax.ejb.Stateless; @Stateless(name="SearchFacade") public class SearchFacadeBean implements SearchFacade,SearchFacadeLocal public SearchFacadeBean(){ 9
Chapter 2 ■ EJB Session Beans 28 Stateless Session Beans Stateless session beans are comprised of the following elements: • A bean class, which contains the business method implementation to be executed • Optionally, one or more business interfaces, allowing different combinations of the bean’s business methods to be presented to client applications The Bean Class A stateless session bean class is any standard Java class that has a class-level annotation of @Stateless. If deployment descriptors are used instead of annotations, then the bean class should be denoted as a stateless session bean in the ejb-jar.xml descriptor. If you use both annotations and deployment descriptors (mixed mode), then the @Stateless annotation must be specified if any other class-level or member-level annotations are specified in the bean class. If both annotations and deployment descriptors are used, then the settings or values in the deployment descriptor will override the annotations in the classes during the deployment process. ■ Note Starting with EJB 3.1, a session bean class can be a sub-class of another session bean class. To illustrate the use of stateless session beans, we will create a SearchFacade session bean that provides various search facilities to client applications regarding available wines. The workflow is as follows: 1. Users of the application will type in or choose one or more search criteria, which will be submitted to the SearchFacade session bean. 2. The SearchFacade bean will access back-end databases to retrieve the requested information. To simplify the code examples in this chapter, we will actually retrieve the list of hard-coded values within the bean class. In later chapters, we will augment the SearchFacade bean to access the back-end database. 3. The bean returns to the client applications the information that satisfied the search criteria. Listing 2-1 shows the definition of the SearchFacade bean. In the following sections of this chapter, we will build the code that will show the preceding workflow in action. SearchFacadeBean is a standard Java class with a class-level annotation of @Stateless. Listing 2-1. SearchFacadeBean.java package com.apress.ejb.chapter02; import javax.ejb.Stateless; @Stateless(name="SearchFacade") public class SearchFacadeBean implements SearchFacade, SearchFacadeLocal { public SearchFacadeBean() { } } 4
CHAPTER 2 EJB SESSION BEANS The Business Interface eessession businenea standard lava interf s met ons will be available for th ewith noother special requirements.This interface siness I e that is impl mented by the p 089 faces can also use annotations,as described in the following list The eRemote annotation can be used to denote the remote business interface The @Local annotation can be used to denote the local business interface. Note Starting with EJB 3.1.session beans support the"no-interface local view."This is a variation of the local view that exposes public methods of a bean class without a separate business interface. If no annotation is specified in the interface,then the public methods of the bean class itself become its own de facto local interface. If your architecture has a requirement whereby the client application(web application or rich client)has to run on a different Java Virtual Machine(JVM)from the one that is used to run the session beans in an EJB container, then you need to use the remote interface.The separate IVMs can be on the same physical machine or on separate machines.If your application architecture is going to use the same IVM for both the client application and the session beans,then performance is improved by using a local interface(which can be the no-interface option). It is possible that your application architecture requires both remote and local interfaces.For example,an enterprise e mignt nave an order entry appncaton that is de veloped using session beans that have business method you could have toerent clent applcations that access the back end ordeenuryppition.as follow suc submit new orders Web Container F.IB Container JSP Session Bean Local JSF Session Calls Bean Session Servlets Bean JVM Application Server Figure 2-3.A web client using local interfaces of session beans 29
Chapter 2 ■ EJB Session Beans 29 The Business Interface A stateless session business interface is a standard Java interface with no other special requirements. This interface has a list of business method definitions that will be available for the client application. A session bean can have a business interface that is implemented by the bean class, generated at design time by tools such as JDeveloper, NetBeans, or Eclipse, or generated at deployment time by the EJB container. Business interfaces can also use annotations, as described in the following list: • The @Remote annotation can be used to denote the remote business interface. • The @Local annotation can be used to denote the local business interface. ■ Note Starting with EJB 3.1, session beans support the “no-interface local view.” This is a variation of the local view that exposes public methods of a bean class without a separate business interface. If no annotation is specified in the interface, then the public methods of the bean class itself become its own de facto local interface. If your architecture has a requirement whereby the client application (web application or rich client) has to run on a different Java Virtual Machine (JVM) from the one that is used to run the session beans in an EJB container, then you need to use the remote interface. The separate JVMs can be on the same physical machine or on separate machines. If your application architecture is going to use the same JVM for both the client application and the session beans, then performance is improved by using a local interface (which can be the no-interface option). It is possible that your application architecture requires both remote and local interfaces. For example, an enterprise might have an order entry application that is developed using session beans that have business methods for submitting new orders and also addressing administrative tasks, such as data entry for the products. Potentially, you could have two different client applications that access the back-end order entry application, as follows: • A web client application (as shown in Figure 2-3) that can be run in the same JVM as the session bean and used to submit new orders Figure 2-3. A web client using local interfaces of session beans