Reprinted from: http://www.java-cn.com/technology/technology_detail.jsp? Id = 781 Total A, Server Participation Structure EJB is a component structure of a Server party, which can develop Java based on Java-based Enterprise-class distributed object application. Using EJB can develop easy-to-upgrade, reliable, secure applications, without independently develop complex distributed object frameworks; EJB can quickly develop service-based applications, quickly establish Java-based service-based components. EJB is designed to realize the portable and reusability of enterprise middleware services. If you are very strange to business, these concepts are useful to you, EJB is a very complex topic, which should be fully explained. In this chapter we discuss the main concept of EJB. First of all, let's discuss development enterprise software for dry? Why is it like the pre-packaged distributed object system of EJB to simplify your life? In the discussion, you will have a macro understanding of the components structure of the server. The server component structure requires us to understand what developers usually need when developers build and configure the components in the server environment? At the same time, we will solve the problems that have emerged around the development of the server will see the need to establish a set of EJB standard architecture. Software components ?? A software component is a code that is used to implement a range of definition interfaces. Components are not a complete application ?? They cannot be run independently. More appropriate, they are considered to be a small problem divided by many large problems. The idea of software components is very useful. Companies can buy a module that can be used to solve a problem, compile it with other components to solve large problems. Component structure ?? In order to make the component development process easier, you need to establish a specification for establishing, management, and maintaining components. Developing components development tools When establishing components, developers should be allowed to concentrate on developing core logic behind components, so that developers do not need to consider too many standard details, so that the application is quickly developed. For example, Ide: Symantec Visual Cafe, IBM's Visualage for Java, Inprise's JBuilder 2, which helps you quickly create and debug components. Managing configured component containers ?? Component container provides a runtime environment for your component. It also provides a universal service for most components. Configuring and maintaining the component tool ?? After purchasing components from the component provider, you also need a set of tools to help configure and maintain these components. Java: Perfect implementation component structure For a component that solves business issues, whether it is a component developer or a component of the component, you must comply with the syntax and semantics of the calling component method. Developers publishing the specifications for calling components, customer code must follow them. In order to prevent developers from providing a new version of component, or change the component specification, the client must rewrite or compile their code, so object-oriented design proposes a new design method: through the implementation from the component Separate the interface. The component interface component logic becomes more efficient in order to separate the interface / implementation, the developer must write customer code for the component interface (this is called an interface-based programming), and the server logic can be changed by this separation. Do not change the customer code. The component structure in Java is now let us know what is the component structure and see those component structures in the Java world. First, you should understand what JavaBeans, JavaBeans Components are small application blocks, you can use JavaBean to set into large components to compile full applications. However, you can't configure a Javabean because a JavaBean is not a full application. JavaBean can help you build a larger configurable software.
Because there is no need to configure, JavaBean does not need runtime environments, nor does it require a container to instantiate, destroy, and provide other services. The application itself is composed of many JavaBeans. Compared, the EJB standard defines a component structure to configure components, known as enterprise-class Beans. Enterprise-level Beans is a relatively large, rough application component. They can be destroyed and can also be used to combine more components into larger application systems. Configurable components are configured in the container that the container provides the runtime service for the component. For example, instantiate. Enterprise Beans and two other Java components are very similar: Applets and servlets. Applets can be configured in a web page, and the browser's AppletViewer provides a container that is running. Servlets can be configured in Web Server, the WebServer Servlet Engine is a container that provides runtime. Enterprise Beans can be configured in the application server, and the application server provides a running container. The truly difference between the three is a small domain that can extend each component type. Applets is a lightweight java program that can be downloaded and running. For example, it can download it from the web server to your browser. Servlets is a network component that can be used to extend the Web Server feature. It is a request / answer, from many clients to request a request, and give them a question. This makes it widely used to perform web tasks. Applets and servlets are suitable for client-side operations. The enterprise-level bean does not extend the client operation, it is a server component, performs a server operation; for example, performing complex operations, performing a large number of commercial transmission. A complete component structure required for the server follows the following way: Developers write reusable components to provide business-writer component containers: to provide runtime environment and service providers to provide development, configuration, and maintenance tools. These methods ensure reusability. Multi-layer structural server configuration is software used to support users simultaneously, safe, reliable, and efficient operations. Services are generally divided into multiple layers. Different functions are achieved for each layer, each layer has one or more components. Note: The layer is an abstract concept, which does not physical it. There is a layered example below: a representative layer: These container components handle user interfaces and user interactions. For example, a representative layer is a separate application that can be written in VB. A web configuration-based representative layer can use Java Servlets, Java Server Pages, or Java Applets. Business Logic Layer: It is a collection of container components used to solve business problems. These components are often used to process high-performance work, and they are used to write, for example: Java, C. Data layers: The business logic layer is used to hold the persistence of the status. The center of the data layer is one or more databases. The advantage of the layering is to try to isolate the layers. Two-layer structure is usually, most configurations are two-layer structure. A merger of the business logic layer and the other two layers: may be merged with the representative layer. It may be combined with the data layer. In terms of layers and business logic layers, such as the layer of the representative layer and the business logic layer as the client, the data layer is used as the server, and the situation of the Thin server is formed. In the two-layer structure, the client application is connected to the data layer through the Database Bridge API. For example: ODBC, JDBC. Such two layers have the following features: The consumer is very high. The database driver must be installed and configured on each customer layer. The database driver exchange is high. Transfer a database driver, you need to reinstall the client driver at each client. The database type transition cost is high. High cost logic transplantation. The database connection is high. Network performance is low. Parting the business logic layer is partially incorporated into the data layer to form the client Thin, and the server FAT is in the case. The N layer structure will represent the layer, the business logic layer, and the data layer are each layer. Features: Low configuration cost. The database exchange cost is low. Low business logic transplantation.
You can configure the security part with the firewall. Resources can be reused. Each layer has a large flexibility J2EE technology: J2EE is an intermediate part service kit that makes development easier for developers of server applications. It contains: EJB: It defines how to write the service party component, provide a standard between components and management of their application servers. EJB is the core of J2EE. RMI and RMI-IIOP: RMI ?? Remote Procedure Call; RMI-IIOP is an extension of RMI, which can use the IIOP protocol to be integrated by CORBA. JNDI: JNDI is used to distinguish between components and other resources on the network. JDBC: It is a bridge to contact the database to launch EJB1.0 months, the first EJB-based application service bea's Weblogic is born. Second, EJB Take EJB Use Divide-And-Conquer to implement the calculation of the server. In fact, the EJB standard defines six different partial collaborative work. Each part is the key to successful EJB configuration. Here, we discuss their role. WHO's WHO IN EJB in the world of EJB, business solutions are divided into four phases: 1. Business logic modular. ERP, finance, e-commerce providers will modularize the product, integration in reusable EJB components, which means that anyone with EJB and J2EE knowledge can use these components. 2, business components need to run in a distributed, enterprise-configured multi-layer environment. This requires different middleware to promote the development of middleware. 3, the application server and reusable components are bundled. 4. Complete system configuration. EJB has a good portability, which is divided into completely different 6 parts: the relationship between 6 parts The Relationship Between EJB Servers and EJB Containers. EJB specification defines the completion of a distributed application based on EJB components. Six roles, these six characters can be taken by different vendors, or a manufacturer acts as a plurality of characters. These six roles are: Enterprise Bean Provider EJB component developers, responsible for writing EJB components, EJB component developers are experts in the application area. Application Assembler application portfoliors, responsible for combining various EJBs into a complete application system. Deployer deployers, responsible for deploying EJB-JAR files that contains EJB components to the application server. The EJB Server Provider EJB server provider is responsible for implementing some underlying system services, such as transaction management, etc. The EJB server provider is an expert in the system. The EJB Container Provider EJB container provider is responsible for providing the EJB component running environment, EJB container providers and EJB server providers are generally served by the same manufacturer, and the supplied product is called application servers. The System Administrator system administrator is responsible for providing an enterprise-level computing and network environment for EJB servers and containers. The physical part of the EJB configuration is divided into the following sections: EJB Container is a space loaded with Enterprise Beans and Enterprise Beans, which is the interface between Beans, and Container must implement the agreement between Beans. The Continer provider should also provide Configure tools to easily configure Beans to make it suitable for a variety of operating environments. EJB Server mainly deals complex underlying tasks, such as distributed objects, distributed transaction processing management, system OS-level access, network, database access, etc. The contract between EJB Server and EJB Container has a detailed description in the EJB 1.0 specification. Most EJB Server providers are also EJB Container providers.
Developing Beans 1. Session Beans Introduction Press EJB into two categories: Session Beans and Entity Beans. Enterprise-class bean classes In order to make Beans can work in any container, Beans must be attached to the interface. In EJB, the implementation of enterprise-level bean components is provided in Enterprise Bean Class. This is a simple Java class that follows the interface. An Enterprise Bean class contains the implementation details of the components. The implementation of the session bean is different from the implementation of entity beans, and a session beans completes a connection or session for a single customer, which survives until the client completes the connection and session, or accidentally suspended. When a new customer is accessing from EJB Server, then EJB Container creates a new session beans instance that runs until the session ends, Session Beans must implement interface javax.ejb.sessionBean. Entity Beans implements interface javax.ejb.entityBean, which describes data in a particular data source, which can be existing in the EJB Container for a long time, and will not disappear with the accidental abortion of the system, and multiple customers can be accessed simultaneously. The EJB specification defines the standard interfaces that many Bean classes can implement. There must be a method that must have all Bean classes. Container calls these methods to manage Beans. All BEAN classes (whether conversation beans or entity beans) The most basic interface that must be implemented is the Javax.ejb.EnterpriseBean interface. Public interface javax.ejb.EnterpriseBean Extends java.io.serializable {} is worth noting: it inherits java.io.serializable. All session beans must implement javax.ejb.sessionBean, all entity beans must implement javax.ejb.entityBean. EJB object When customers want to use an instance of Enterprise Bean Class, customers don't have to call methods directly on the actual instance, call The process is intercepted by the EJB container, and the bean instance is represented by the object in the container. 1, Enterprise Bean Class cannot be called directly over the network, we know that the EJB container can manipulate the network, so it is packaged into objects that can be used on the network through the container. 2. By intercepting the request, the container can automatically perform many necessary management work. 3, the EJB container can track which method is called, displaying its usage, etc. on the system administrator's user interface. Therefore, the EJB container can be regarded as a layer existing between customer code and bean. This indirect layer uses a separate network object to represent yourself, this object is called an EJB object. EJB objects as part of the vessel physics; all EJB objects have code for special requirements for containers. Therefore, the container provider provides specialized tools to generate class files from the EJB object. Remote Interface We have learned that the BEAN customer calls the method on the EJB object instead of calling the bean, in order to perform it, the EJB object must copy each business method in the bean class. However, how can I make the automatically generated EJB object know which method is copied? This uses a special interface written by the bean provider, and this interface is copied to all business logic methods associated with the bean class. This interface is called a remote interface. This interface must follow the definition of the EJB specification, and all remote interfaces must inherit from the general interface provided by Sun, Javax.ejb.ejbObject.
EJB object public interface javax.ejb.EJBObject extends java.rmi.Remote {public abstract javax.ejb.EJBHome getEJBHome () throws java.rmi.RemoteException; public abstract java.lang.Object getPrimaryKey () throws java.rmi.RemoteException; public abstract void remove () throws java.rmi.RemoteException, javax.ejb.RemoveException; public abstract javax.ejb.Handle getHandle () throws java.rmi.RemoteException; public abstract boolean isIdentical (javax.ejb.EJBObject) throws java. Rmi.RemoteException;} The above is the method that must have for all EJB objects, you don't need to implement these methods, the implementation of these methods, automatically generated by the container when generating an EJB object. The client code works with Bean by calling Javax.ejb.ejbobject. Java RMI and EJB objects You should notice: java.ejb.ejbobject inherits Java.rmi.Remote. The java.rmi.Remote interface is part of the Java Remote Method Call (RMI), any object that implements Java.rmi.Remote is the RMote object, which can be called by another Java virtual machine. The remote interface is implemented by the EJB object provided by the container, and also indirectly implements Java.rmi.Remote, which means that your EJB object is fully compliant with the network needs, can be called by other Java virtual machines on the network. Of course, the EJB interface must also comply with EJB specification. The EJB remote interface must comply with Java's RMI remote interface specification. For example: Error handling, the same is true. The remote interface must also follow the Java RMI parameter transfer specification. Not anything can be transferred to the network through the VM method, and the passing parameters must comply with the RMI type. EJB also inherits the advantage of RMI, for RMI, the physical address of the remote object you are calling is invisible. This feature also applies to EJB. Customer code does not have to care about the use of EJB objects that are passed on the neighboring computer or from the INTERNAT. In this way, the EJB object can be in the same Java VM at the client. EJB guarantees the transparency of local distributed components. This transparent is very necessary for multi-layer configurations. The client code is very easy to transplant, unrecorded to a special multi-layer configuration. The EJB container can be implemented locally in optimization. HOME object We see that the client code handles the EJB object, and does not directly operate Beans. So how do the client get the reference of the EJB object? The client does not instantiate the EJB object directly. Because the EJB object can exist in different machines. Similarly, EJB makes local transparency, so the client does not know the exact location. The client code gets the reference of the EJB object through the EJB object factory. This plant is a Home object in the EJB specification. It mainly plays the role: establish an EJB object. Find the existing EJB object. Delete the EJB object. In some details, the EJB object plant is the same as the EJB object. Home Interface Home Interface Simple Defines the method of establishing, deleting, and looking for EJB objects. The HOME object of the container implements the HOME interface. Typically, EJB defines many methods that all HOME interfaces must support, these must be defined on the Javax.ejb.ebHome interface, and the Home interface must inherit the java.ejb.ebhome interface.
public interface javax.ejb.EJBHome extends java.rmi.Remote {public abstract EJBMetaData getEJBMetaData () throws java.rmi.RemoteException; public abstract void remove (Handle handle) throws java.rmi.RemoteException javax.ejb.RemoveException; public abstract void remove (Object primaryKey) throws java.rmi.RemoteException, javax.ejb.RemoveException;} javax.ejb.EJBHome interfaces attention javax.ejb.EJBHome inherited java.rmi.Remote, which means home interface also supports remote RMI objects The passing parameters and RMI are also the same. HOME Objects All HOME objects The method configuration descriptor configuration descriptor allows the EJB container to provide an implicit middleware service to an enterprise-level Bean component. An implied middleware service is a service that Beans can get unwanted to decode any middleware API and automatically obtain a service. The special properties of Beans are ultimately, you also need to have a property file based on Java-based bean. BEAN reads these properties at runtime, which will be used when using the Bean function. Once the EJB-JAR file generates the class, HOME interface, remote interface, configuration descriptor, and bean properties, we can pack them into an entity. This entity is called an EJB-JAR file. This is a compressed file. Establishing an EJB-JAR file What is a session bean a session beans to complete a connection or session for a single customer, which survives until the client completes the connection and session, or accidentally abort. Session Beans must implement interface javax.ejb.sessionBean. The main difference between the session bean's survival session bean and entity beans is the length of their survival. The survival of the session bean is short. It is quite equivalent to the customer's session time. The EJB container destroy the session bean when the client is connected. In contrast, the entity bean can survive the time, and the entity bean is part of permanent access, such as a database. Session beans cannot save permanent storage data, but it can perform database operations. All session beans need to manage the Callback method, and the container timing calls it to make a warning for the important events of BEAN. This method can only be called by the container.
How Conversational versus Nonconversational Session Beans Session Bean write writing session bean class must implement the javax.ejb.SessionBean interface public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean {public abstract void setSessionContext (SessionContext ctx) throws java.rmi. RemoteException; public abstract void ejbPassivate () throws java.rmi.RemoteException; public abstract void ejbActivate () throws java.rmi.RemoteException; public abstract void ejbRemove () throws java.rmi.RemoteException;} session bean and entity bean have inherited The Javax.ejb.EnterpriseBea interface allows us to look at various methods in the interface: SetSessionContext (SessionContext CTX) container calls this method to connect to the bean through session context. The bean can query the status of the current event and the current security status by session context to the container. import javax.ejb *;. public class MyBean implements SessionBean {private SessionContext ctx; public void setSessionContext (SessionContext ctx) {this.ctx = ctx;} ...} ejbCreate (...) is used to initialize your session bean, can be defined The ejbcreate () method of multiple different parameters is initialized in different ways. import javax.ejb *;. public class MyBean implements SessionBean {private int memberVariable; public void ejbCreate (int initialValue) {this.memberVariable = initialValue;} ...} ejbCreate () callback method is invoked may be a container, the client The code cannot call it, because the client cannot directly handle Beans ?? They must pass through the container, but the client must use some way to pass parameters to the EJBCREATE method, and the client provides initialization parameters. The HOME interface is an interface factory that the client is used to initialize the call. You must copy each ejbcreate () method in the Home interface, for example, if you have the following EJBCREATE Method in the Bean class, you have the following EJBCREATE (INT i) throws ... then you must have the following in your HOME interface CREATE () Method Public Void Create (INT i) THROWS ... Client calls the CREATE () method in the Home interface, pass the parameters to ejbcreate (). Ejbpassivate () If there are too many instance beans, the EJB container can pass some of them, write them to temporary export spaces such as databases or file systems. The container releases the space they apply.
Import javax.ejb. *; public class mybean imports sessionbean {public void ejbpassivate () {
In order to locate resources in J2EE, the following two steps must be implemented: 1. The J2EE will bind nickname to the resource with "nickname" associated resources in the configuration descriptor. 2, the client's client uses the nickname positioning resources in JNDL. How to use JNDL Positioning Home Objects The client does not have to care about the home object in the network. JNDL provides nicknames for the Home object to locate the Home object. The reference of the Home object can be obtained by nickname. For details, the client code must perform the following steps to get a reference through JNDL. 1. Establish an environment. You must configure that the directory service will be used, including the username, password required to verify the identity. 2. Establish an initial context. The initial context is the local starting point for the connection to the directory structure. The set environmental properties are obtained by the initial context. 3, get the home object. Execute a lookup () operation, return an RMI remote object. Home object obtained with reference to / * * Get System properties for JNDI initialization * / Properties props = System.getProperties (); / * * Form an initial context * / Context ctx = new InitialContext (props); / * * Get a reference to The Home Object - The * Factory for EJB Objects * / MyHome Home = (MyHome) CTX.lookup ("MyHome"); After establishing an EJB object After getting Home object, you can use the Home object as a factory that creates an EJB object. Call the CREATE () method to establish an EJB object. MyRemoteInterface ejbobject = home.create (); no parameters are because stateless beans do not require initial parameters. Calling method The client has an EJB object after the EJB object can be called by it. When the client calls a method on the EJB object, the EJB object must select a bean instance to answer. EJB objects can create a new instance or reuse the existing instances. EJBObject.Add (); destroying the EJB object calls the REMOVE () method on the EJB or Home object to destroy the EJB object. EJBOBJECT.Remove (); stateless session bean foundation stateless session bean is a component that can imitate the business process, which can be performed in separate method calls. The Stateless Session bean is not able to maintain a status of a call customer. In a method call, the Stateless Session bean maintains the status of the calling customer. When the method is executed, the status is not maintained. After the call is completed, the Stateless Session bean is immediately released into the buffer pool, so the Stateless Session bean has good scalability and can support a large number of users. The feature of stateless session beans does not have a dialog stateless session bean can have internal states, and their status cannot be customized for special clients. This means that all stateless beans have no differences for the client, and the client cannot separate them. The client must pass all necessary client data to the parameter of the business logic method to the stateless bean, and the stateless bean can obtain the required data from an external resource (such as a database). Initializing stateless beans have only one way. We know that the initialization of session beans calls the ejbcreate () method because the stateless session bean cannot reserve the state between the method call, so it cannot pass the client to ejbcreate () to transfer data. Reserved. Call EJBCREATE () or CREATE () without parameters.
Containers can aggregate and reuse stateless sessions beans build "Hello, World!" Remote Interface package com.wiley.compbooks.roman.session.heloworld; import javax.ejb. *; Import java.rmi.RemoteException; import java.rmi. Remote; / ** * This is the HelloBean remote interface * * This interface is what clients operate on when * they interact with EJB objects The container * vendor will implement this interface;.. the * implemented object is the EJB object, which * . delegates invocations to the actual bean * / public interface Hello extends EJBObject {. / ** * The one method - hello - returns a greeting to the client * / public String hello () throws java.rmi.RemoteException;} Source 4.1 Hello .java. Hello interface inherits the EJBOBJECT interface, EJBObject inherits the Remote interface, so Hello can throw RMI anomalies. Establish a bean to achieve business methods: Hello (). He realized the javax.ejb.SessionBean interface package com.wiley.compBooks.roman.session.helloworld; import javax.ejb *;. / ** * Demonstration stateless session bean * / public class HelloBean implements SessionBean {// //. EJB-Required methods // public void ejbcreate () {system.out.println ("ejbcreate ()");} public void ejbremove () {system.out.println ("ejbremove ()");} public void EJBACTIVATE ) {System.out.println ( "ejbActivate ()");} public void ejbPassivate () {System.out.println ( "ejbPassivate ()");} public void setSessionContext (SessionContext ctx) {System.out.println ( "SetSessionContext ()");} /// Business method Methods // public string hello () {system.out.println ("Hello ()"); return "Hello, World!";}}} Source 4.2 Hellobean.java Note: You don't need to implement your own remote interface, the initialization method does not have parameters. When destroying beans, use a relatively simple EJBREMOVE () method. Ejbactivate () and EJBPassivate () methods do not need to be applied in stateless session beans, so these two methods are empty. Establish "Hello, World!" HOME Interface HOME interface inherited Javax.ejb.ejbhome.
The HOME interface extends a method that does not have a parameter for the EJB object ?? Create () method. package com.wiley.compBooks.roman.session.helloworld; import javax.ejb *;. import java.rmi.RemoteException; / ** * This is the home interface for HelloBean This interface * is implemented by the EJB Server's. glue-code tools -. the * implemented object is called the Home Object and serves * as a factory for EJB Objects * * One create () method is in this Home Interface, which * corresponds to the ejbCreate () method in HelloBean *. / public interface HelloHome extends EJBHome {.. / * * This method creates the EJB Object * * @return the newly created EJB Object * / Hello create () throws RemoteException, CreateException;} creat method throws a java.rmi.RemoteException And aavax.ejb.createException. Exception. Write configuration descriptors In EJB 1.0, the configuration descriptor is a Java object stored on the disk as a file. In EJB1.1, the configuration descriptor is an XML document. The EJB container or IDE environment should provide a tool for generating a configuration descriptor. Configuration Descriptor Settings Bean Home's Name Enterprise Bean Class Name HOME Interface Class Name Rear Interface Class Name Re-Entrant Status or Status Session Time Hellobean Configuration Descriptor Environment Properties Bean Adapts to different special environments. EJB-JAR file We need to pack our required files into an EJB-JAR file. Enterprise-level Bean Remote Interface Home Interface Configuration Descriptors, including attributes These must be included in the EJB-JAR file. In EJB1.0, the JAR file has a list of text files. It represents the details of JAR. It is used to identify which business bean is in the EJB-JAR file. In EJB1.1, the XML file contains all necessary information. Generate EJB-JAR file JAR CMF ../manifest helloworld.jar * Configure the Bean Finally, we also need to configure Bean in the EJB container.
Often enable steps: EJB-JAR files Test container tools to generate EJB objects and Home object container tools to generate the Stubs and Skeletons required by RMI and the Skeletons write-free bean customer code package com.wiley.compbooks.Roman.Session.HelloWorld Import javax.ejb. *; import javax.naming. *; import java.rmi. *; import java.util.properties; / ** * this class is an esample of client code That Invokes * Methods on a Simple Stateless Session . bean * / public class HelloClient {public static void main (String [] args) {try {/ * * Get System properties for JNDI initialization * / Properties props = System.getProperties (); / * * Form an initial context * / Context CTX = New InitialContext (PrOPS); / * * Get a reason to the home object * (The factory for ejb objects) * / hellohome home = (HelloHome) CTX.lookup ("HelloHome"); / * * Use the factory To create the ejb object * / hello hello = home.create (); / * * call the hello () method, and print it * / system.out.Println (Hello Hello ()); / * * Done with EJB Object, so remove it * / hello.remove ();} catch (exception e) {E.PrintStackTrace ();}}} client code executes tasks: positioning HOM E Interface The HOME interface creates an EJB object to call the Hello () remove the Hello () remove the EJB object on the EJB object, run the application server. For BEA's WebLogic, perform T3Server client execution: java -djava.naming.Factory.Initial = WebLogic.jndi.tengahinitialContextFactory -djava.naming.Provider.URL = T3: // localhost: 7001 com.wiley.compbooks.roman. SESSION.HELLOWORLD.HELLOCLIENT server output: setsessionContext () Ejbcreate () Hello () EJBREMOVE () Client Output: Hello, World!
Status Session Bean Basics STATEFUL Session Bean can maintain a status of a call customer, and maintain this state in different method calls, because for each concired user, there must be a corresponding stateful session bean, in order to improve the system The efficiency, Stateful Session beans can be written to a secondary storage device (such as a hard disk) after a certain customer idle time, and after the customer issues a new call request, returns to the memory from the secondary storage device. But under multi-users, the Stateless Session Bean has higher operating efficiency than Stateful Session Bean. The Javax.ejb.EnterpriseBean interface inherits java.io.serializable to implement write read operations. When the EJB container calls the ejbpassivate () method passivates the bean, you can write it to the secondary storage device, and the container calls the ejbactivate () method to activate the bean, and read it from the secondary storage device. Status Bean's passivation process counting Remote interface remote interface defines a business method count (), which will be implemented in the enterprise bean class.
Active state bean package com.wiley.compBooks.roman.session.count; import javax.ejb *;. Import java.rmi.RemoteException; / ** * These are CountBean's business logic methods * * This interface is what clients. operate on when they * interact with EJB objects The container vendor will implement this interface;.. the implemented object is * the EJB Object, which delegates invocations to the * actual bean * / public interface Count extends EJBObject {/ ** * Increments the int stored as conversational state * / public int count () throws RemoteException;} Source Count.java package com.wiley.compBooks.roman.session.count; import javax.ejb *;. / ** * Demonstration Stateful Session Bean This. bean is * initialized to some integer value and has a business * method that increments the value. * * This example shows the basics of how to write a stateful * session bean and how passivation / activation works. * / public class CountBean implements SessionBean { Private sessionContext CTX; // The Current Counter IS OUR Conversational state. public int val; // // business methods /// / ** * counts up * / public int count () {system.Println ("count ()"); Return Val;} // // ejb-required methods // public void ejbcreate (int vali) throws createException {this.Val = val; system.out.println ("ejbcreate ()");} public void ejbremove () {system.out.println "ejbremove ()");} public void ejbactivate () {system.out.println ("ejbactivate ()");} public void ejbpassivate () {system.out.println ("ejbpassivate ()");} public void SetSessionContext (sessionContext CTX) {}} Source CountBean.java bean implements javax.ejb.sessionBean. So it must define all methods defined by the sessionBean. Ojbcreate () initializes the parameters of VAL. It will be the initial state of the Counter.
The VAL variable is protected during passivation and activation of the bean. Counting bean home interface package com.wiley.compBooks.roman.session.count; import javax.ejb *;. Import java.rmi.RemoteException; / ** * This is the home interface for CountBean This interface * is implemented by. the EJB Server's glue-code tools - the * implemented object is called the Home Object and serves * as a factory for EJB Objects * * One create () method is in this Home Interface, which * corresponds to the ejbCreate (). method in the CountBean file. * / public interface CountHome extends EJBHome {/ * * This method creates the EJB Object. * * @param val Value to initialize counter to * * @return The newly created EJB Object. * / Count create (int VAL) THROWS RemoteException, CreateException;} Source Counthome.java. Counting Bean Configuration Descriptor Count BEAN Configuration Descriptor Counting Bean Environment Property Generates Count BEB-JAR File Count BEAN Client Code Package Com.wiley.compbooks .roman.session.count; import javax.ejb. *; import javax.naming. *; import java.util.properties; / ** * this class is a Simple Example of Client Code That Invokes * Methods On A Simple Statel ess Enterprise Bean. * * We create 3 EJB Objects in this example, but we allow * the container to have only 2 in memory. This illustrates how * beans are passivated to storage. * / public class CountClient {public static void main (String [] args) {try {/ * * Get System properties for JNDI initialization * / Properties props = System.getProperties (); / * * Get a reference to the Home Object - the * factory for EJB Objects * / Source CountClient.java 1. Just JNDL initialization context 2, use the JNDL positioning home interface 3, use the Home object to establish three different count EJB objects, so the session 4 is established with three different clients 4, the configuration descriptor is limited to only There are two beans work, so three beans must be passivated. Print a message when ejbpassivate () is called. 5. Call the count () method on each EJB object, call the ejbactivate () method to activate the bean, which prints a message. 6, the last EJB object is deleted.
Package com.wiley.compbooks.roman.session.count; import javax.ejb. *; import javax.naming. *; import java.util.properties; / ** * this class is a simple esample of client code invokes * methods on a simple Stateless Enterprise Bean. * * We create 3 EJB Objects in this example, but we allow * the container to have only 2 in memory. This illustrates how * beans are passivated to storage. * / public class CountClient {public static void main (String [] args) {try {/ * * Get System properties for JNDI initialization * / Properties props = System.getProperties (); / * * Get a reference to the Home Object - the * factory for EJB Objects * / Context ctx = new initialcontext (props); counthome home = (countHome) CTX.lookup ("countHome"); / * * an array to hold 3 count ejb Objects * / count count [] = new count [3]; int COUNTVAL = 0; / * * Create and count () on each member of array * / system.out.println ("instantiating beans ..."); for (int i = 0; i <3; i ) {/ * * Create an EJB Object and Initialize * IT T o the current count value. * / count [i] = home.create (countval); / * * add 1 and print * / countval = count [i] .count (); system.out.println (countval); / * * Sleep for 1/2 second * / thread.sleep (500);} / * * let's call count () on each ejb Object to * make Sure the beans around passidid and * activated prot ou. * / System.out .println ("Calling Count () on beans ..."); for (int i = 0; i <3; i ) {/ * * add 1 and print * / countval = count [i] .count (); System.out.println (Countval); / * * Sleep for 1/2 second * / thread.sleep (500);} / * * done with ejb objects, so remove the * / for (int i = 0; i < 3; i ) {count [i] .remove ();
}} Catch (Exception e) {e.printStackTrace ();}}} Source CountClient.java run the client: For WebLogic BEA executes: java -Djava.naming.factory.initial = weblogic.jndi.TengahInitialContextFactory -Djava. Naming.Provider.ur = T3: // localhost: 7001 com.wiley.compbooks.roman.session.count.countClient client output: instantiating beans ... 1 2 3 Calling count () on beans ... 2 3 4 service-ended output: ejbCreate () count () ejbCreate () count () ejbCreate () ejbPassivate () count () ejbPassivate () ejbActivate () count () ejbPassivate () ejbActivate () count () ejbPassivate () ejbActivate () count () ejbctivate () ejbremove () ejbactivate () ejbremove () ejbremove ()
Add functions for Beans EJB context: The portal to the container exists as follows: 1. About the Home object of the bean and the information of the EJB object 2, the current transaction information of beans. 3, for the customer's authorized security information. BEAN can determine the security level required by the customer to perform the security level by querying the environment. 4, bean's environmental properties. The container saves all of this information in a target called EJB Context Object. The EJB context as the physical part of the container, can be accessed by bean. These accesss allow beans to get current status and change the current state. The context can be changed in the life of the bean. EJB1.0 javax.ejb.EJBContext the interface: public interface javax.ejb.EJBContext {public javax.ejb.EJBHome getEJBHome (); public java.util.Properties getEnvironment (); public java.security.Identity getCallerIdentity (); public boolean isCallerInRole (java.security.Identity); public javax.jts.UserTransaction getUserTransaction (); public void setRollbackOnly (); public boolean getRollbackOnly ();} context session bean bean into different context according to: entity context and the session context. They are used for session bean and entity bean javax.ejb.EJBContext public interface javax.ejb.SessionContext extends javax.ejb.EJBContext {public javax.ejb.EJBObject getEJBObject ();} Note: SessionContext EJBContext interface extends the interface, in The method defined in EJBContext provides the access path to the session bean. For session beans, setSessionContext, which is defined in the Javax.ejb.SessionBean interface. For entity beans, call setentityContext. SessionContext.GeteJBObject () In EJB, Beans can be used as a client of other beans. If a bean needs to call additional beans, the getEJBObject () method is required. In Java, the object can save its own reference using this keyword. In EJB, Bean cannot communicate objects using this keyword, because all methods on all customers call beans are indirectly calling the EJB objects of Beans. BEAN can pass itself to the EJB object using this keyword. Understanding the security of EJB First, the client must be identified. Second, the client must be authorized. Step 1: Differentially different EJB containers have different approaches client methods. For example: BEA's WebLogic, provides different usernames and passwords when different client code uses JNDL positioning home objects.
Properties props = System.getProperties (); props.put (Context.SECURITY_PRINCIPAL, "EmployeeA"); props.put (Context.SECURITY_CREDENTIALS, "myPassword1"); Context ctx = new InitialContext (props); // Use the initial context To lookup Home Objects ... EJB does not develop specific specifications, so this affects the portability. To understand this, check the documentation of various containers. When running this code, the application server will verify your username and password, which is the application server specification. Many application servers allow for setting usernames and passwords in the properties file. This file will be read by the application server at runtime. The high-level server supports the integration of the existing verification system. For example, store the username and password list in the LDAP server. Step 2: Authorization can only call methods in the bean only after authorized clients. There are two ways to verify authorization in EJB: Declarative, and Programmatical. That is, all authorization inspections are performed by the container, and an authorization check is performed in the program. When the Declarative Authorization Check, you must declare the authorization needs of Beans in the configuration descriptor. For example, an example using a configuration descriptor for a Wea's WebLogic server: (AccessControllentries SubmitpurchaseOrder [Employees] ApprovePurchaseOrder [Managers]; End AccessControlEntries container will automatically perform security checks at runtime. Point out the java.lang.securityException exception. Programmatic Authorization Check, you must query the EJB context to get the current client's authorization information. CallerinRole (Identity Role) and getCallerIdentity () are called by two methods.