Ninth, JavaBean and RMI

zhaozj2021-02-16  54

9.1 Basic Concept of Javabean

9.1.1 Background of JavaBean generated

The software industry has always been the core of the computer industry. When the computer has just been admitted, the computer software is basically in the slow development period. At that time, the computer software language used was a machine language that was closely related to hardware, and then the assembly language appeared. As the computer is increasingly involved in people's life, the software has become more complicated. So the advanced high-end language-centric high-level language is the low-level language of the computer development, of which the emergence of the Fortran language in the late 1960s is a change, and the advanced language like Basic and Lisp has also been correspondingly produced. These languages ​​allow programmers to be extravasted by specific hardware structures, using terminology closer to actual problems to express their design ideas.

But on the other hand, this new degree of freedom makes the continuous complex application need to have more complex software. Software industry freedom and complexity increases, software development teams continue to expand, and cost is also increasing. The software industry also has a constant cost-to-cost and rapid and reliable software development method, so in the late 1990s, the idea of ​​component-based software development has been widely valued and applied.

Software components refer to software sections that can be independently separated, easy to reuse. JavaBean is a software component idea based on Java platform. JavaBean is also an application programming interface (API) independent of platform and structure. JavaBean retains the technical essence of other software components, and increases the technical features ignored by other software components, making it the basis for complete software component solutions and is conveniently used in the network world on portable Java platforms. .

In fact, you can understand the components into the building blocks playing in childhood, and software that can be placed with components can understand the works of different shapes you use by building blocks. This metaphor may allow you to understand why the components build apps make applications more stable and fast than other methods. Because the software components are reusable, it is definitely a lot of applications, so when you use it, the probability of error is definitely smaller than you rewrite the same function. It will be easier to understand, which is easy to understand, just like a bridge that you use a bridge that you use wood to make a bridge with wood.

Javabean is also a successful component model. If you have used JBuilder, then you will definitely benefit from the convenient control it provides, and these controls are almost javabean. In fact, you have already used Javabean unconsciously, but you have not noticed it. 9.1.2 JavaBean Basic Concept

Although JavaBean and Java have a clear boundary, there is still a place where the JavaBean and Java is still more confusing, such as reuse, Java language can also create reusable objects for users, but it doesn't Manage rules or criteria for these objects interaction, users can use pre-established objects in Java, but this must have a rich knowledge of the interface at the code hierarchy. For JavaBeans, users can use a variety of JavaBean components in the application constructor tool without having to write any code. This function of using multiple components simultaneously without considering its initialization is an important extension of the current Java model, so JavaBean can also be said that JavaBean is an extension of the Java language in component technology.

If you really want to definition, the JavaBean definition is that JavaBean is a reused platform independent software component that can perform visual operations directly in the software constructor tool. In the above definition, the software constructor can be a web page constructor, a visual application constructor, a GUI design constructor, or a server application constructor. JavaBean can be a simple GUI element such as buttons and scroll bars; can also be a complex visualization software component, such as a database view. Some JavaBean is not a GUI performance form, but these Javabeans can still use the application constructor to be combined, such as many controls on JBuilder actually do not have a GUI form, but you can still drag and drop them in your application. Generate the corresponding code. A JavaBean and a Java Applet are very similar to a very simple Java class that follows some strict protocol. JavaBean has all the advantages of Java language, such as cross-platform, but it is an extension of Java in component technology, so many aspects it and applet are very similar, applet also has all the advantages of Java language, and Java is browsing Extension of the server. In fact, they are all strictly followed by the Java classes of some protocol, and their existence is inseparable from the powerful support of the Java language.

9.1.3 Properties, events and methods of JavaBean

Basically, JavaBean can be seen as a black box, that is, it is only necessary to know its function without the software equipment of its internal structure. The black box only introduces and defines its external features and interfaces with other parts, such as buttons, windows, colors, shapes, and the like. As a model of a black box to view JavaBean as a component building block for accepting events and processing events for actions.

A JavaBean consists of 3: (1) Properties JavaBean provides a high-level property concept, attribute is not just a traditional object-oriented concept in JavaBean, which also got a property read and attribute written Support for the API. Attribute values ​​can be performed by calling the appropriate bean method. For example, it may be a name attribute that may be a name attribute. The value of this property may need to call the string getName () method to read, and the write attribute value may need to call the Void SetName (String Str) method.

Each JavaBean property should usually follow simple method naming rules so that the application constructor tool and end user can find the properties provided by JavaBean, then query or modify the attribute value, and operate the bean. JavaBean can also make a timely response to changes in property values. For example, a JavaBean that displays the current time, if the clock is changed, the clock will immediately redraw, display the time of the current specified time zone.

(2) Method's method in javabean is the usual Java method, which can be called from other components or in a script environment. By default, all BEAN's public methods can be called outside, but Beans generally leads to a subset of their public methods.

Since JavaBean itself is a Java object, the method called this object is the only way to interact with its interaction. JavaBean strictly abides by object-oriented class design logic and does not allow the external world to access its fields (no public fields). In this way, method call is the only way to contact Bean.

Different from ordinary categories, for some beans, low-level mechanisms with calling instance methods are not the main ways to operate and use beans. The public bean method is reduced to auxiliary status in Bean operation because two advanced bean features - properties and events are better ways to interact with beans. Therefore, Bean can provide the public method to allow customers, but it should be recognized that the Bean designer wants to see that the functionality of the BEAN is reflected in the attributes and events, not in manual calls and each method.

(3) The main way of the event (Event) bean and other software components is to send and accept events. We can regard the BEAN's event support function as an input and output pin in the integrated circuit: Engineers connect the pin together to make components to communicate. Some pins are used for input, some pins are used to output, equivalent to sending events and reception events in the event model.

Events provide a method of sending notification to other components for JavabEan components. In the AWT event model, an event source can register the event listener object. When an event source detects a certain event, it will call an appropriate event processing method in the event listener object to handle this event.

It can be seen that JavaBean is indeed an ordinary Java object, but it follows some special agreements.

9.1.4 Characteristics of JavaBean

JavaBean 1.0 specified component model specifies the following characteristics:

(1) Inland Province: Making components can publish their support and attributes of their support, but also mechanisms that support this mechanism in other components (such as the development tools such as Beans).

(2) Properties: The appearance and behavior characteristics can be changed when designing Bean. The development tool has known its attributes by taking the bean, thereby issuing its properties.

(3) Customization: Bean can be customized when designing its properties. There are two ways to support customization: By using the properties editor of Beans, or use more complex bean customizers.

(4) Communication: BEAN is communicated with each other by events. The development tool can detect an event that a bean can receive and initiate.

(5) Continue: Make the bean to store and restore its status. After the attribute of a bean is modified, it can be saved by the end of the object and can be recovered when needed.

You may be curious, how is so many features to be implemented in Javabean? Javabean has a lot of Java language, and the next section we will discuss how JavaBean is implemented, this is a bit complicated, so please play a spirit, continue our JavaBean tour.

9.1.5 Introduction to the JavaBean Characteristics

1. Attribute 2. Inner province and customization

3. continued

4. event

1. Attributes

Bean's properties describe its appearance or behavioral characteristics, such as color, size, and the like. Properties can be obtained and set through the GET / SET method at runtime. End users can change them through a GET / SET method for a particular property. For example, for the color attribute of the bean, the end user can change this color attribute through the attribute dialog provided by the bean. The change in color is actually achieved by the following method:

Public Color getFillColor (); Public Void SetFillColor (Color C);

This basic GET / SET method naming rule defined is called simple properties. There is a class of properties represented by a boolean value in the simple properties called Boolean properties.

The JavaBean API also supports index properties, which is very similar to the array in traditional Java programming. Index attributes include the same elements of several data types, which can be accessed through an integer index value, and thus referred to as index properties. Attributes can index a value that supports a certain range, this property is a simple property. Corpled INT specified. Index properties have four access methods, and their numerical arrays can be accessed by an element, or you can access the entire array:

Public void setlabel; public string getlabel (int index); public void setlabel (String [] labels); public string [] getLabels ();

The similar index value with the standard Java array may be outside the index attribute array. At this time, the visitor method for operating the index property is generally throwing an ArrayIndexOutOfboundSexception running environment exception, which is the same as the behavior that is performed when the standard Java array index exceeds the range.

Relative to simple properties is associated attributes and restriction properties. These two properties are modified when they are running or design, automatically notify the external world, or have the ability to reject the properties set to a value. Association properties make a notification to other Beans and containers when the property changes. Association Attributes generate a PropertyChangeEvent event when changing, passes to the listener of the registered PropertyChangeListener associated. You can register or revoke multiple broadcast event listeners by the following method: Public Void AddPropertyChangelistener (PropertyChangelistener L); PROPERTYCHANGELISTENER L);

PropertyChangeListener is an interface that when the relevant external part needs to be associated with a property, it must call the AddPropertyChangeListener () method to provide a suitable object that implements the PropertyChangeListener interface. The PropertyChangeListener interface is used to report changes to the associated properties, especially when an associated property value changes, call the PropertyChange () method on all registered PropertyChangeListener interfaces. This method accepts a PropertyChangeEvent object that contains information about the specific properties to modify and its new and old values. The figure below shows how the associated property works:

The primary event that occurs in the above figure is to send a property modification notification from the bean to a listener. The listener must first register the bean before deciding to modify the specific properties by checking the PropertyChangeEvent object sent with the notification.

The JavaBean API also supports another method for registering the listener and a specific associated property. If a bean developer wants to provide a listener registration on a single property, he must support a pair method for each such property: add

Listener () and Remove

Listener (). This works on the method just as previously introduced to the global event listener registration method, but both methods are for specific properties. One of the following examples define these two ways named NAME:

Public Void Addnamelistener (PropertyChangelistener L); PROPERTYCHANGELISTENER L);

When the Bean external related components are registered on the Name property, it simply invokes the AddNameListener () method to register itself. When the Name property is modified, a notification to the event listener is sent by calling the PropertyChange () method. This is the same as the previous introduction, just here the listener receives only a notification of the Name property.

The restriction attribute is internal verification, if unqualified will be rejected. Users can know the rejected attributes through an exception. The restriction attribute is verified by VETOABLEELISTENER interface. You can use the following method to register or revoke the interface: Public Void AddVetoableChangelistener (VetoableChangelistener V); Public Void RemoveveToableChangeListener (VetoableChangeListener V);

The processing mechanism for restriction attributes and associated properties is very similar. When the modification value of the property reaches the listener, the listener can make modifications to the reject attribute by throwing the PropertyveToException exception. If an exception is thrown, this bean is responsible for processing this exception and restores the original value of this restriction attribute.

Similar to the associated properties, the restriction attribute also supports an event listening method for a single attribute. Here is an example: public void addnamelistener (VetoableChangelistener L); PUBLIC VOID Removenamelistener (VetoableChangelistener L);

2. Inner province and customization

BEAN is usually developed into generalized components that are configured by developers when establishing an application. This is achieved by two Java technology accompanying JavaBeans API. The first is that Java reflects the API, which is a class for the perspective class file and the properties and methods displayed. The second is the Java serialization API for generating permanent storage of classes, including its current state. Both techniques are used to enable Beans to explore and display with build tools, and modify and store them for specific applications.

JavaBean's internal provision showing the properties, methods, and events of Beans. The internal provincial process is actually very simple. If there is a method of setting or acquire attribute type, it is assumed that the bean has this attribute, which can be used: public

get

();

Public void set

(

p);

If you only find a get / set method, make sure PropertyName is only read or write.

In addition to the above-mentioned built-in internal provinces and custom methods, the JavaBean API also provides displayed interface BeanInfo, which is used in the Bean designer to show the properties, events, methods, and all global information of Beans. You can define your own bean information class by implementing the BeanInfo interface: Public Class MyBeanInfo IMPLEments BeanInfo ..

The BeanInfo interface provides a range of methods for accessing Bean information, and Bean developers can also provide a dedicated description file for BeamInfo class to define bean information.

3. continued

JavaBean is a component-dependent component, and the status may change because of some of the operations or in development. When the state of the bean changes, the designer can save the changed state, which is the continuation of JavaBean. The continuation of the JavaBean state can be automatically saved through the serialization mechanism of the Java object, or by customizing the status of the BEAN object in the designer.

4. event

JavaBean communicates between Beans by passing events. BEAN tells another bean with an event to take actions or tell their status. The event is registered or published from the source listener and passes to one or several target listeners through method calls.

JavaBean's event model Similar to the event model of AWT. The event model in JavaBean is defined by the event source and event destination. The event source is the initiator of the event, which triggers one or more event destination. Event source and event goals create a group of methods for event source adjustment event listeners.

This section describes the basic concepts of JavaBean and some internal mechanisms of JavaBean. Now you should already know what Javabean is something, and you have a certain understanding of the specifications and some implementation of Javabean, such as you should know that Javabean has What is the characteristics, it should also be aware of the mechanisms. However, you must have doubts, because you haven't seen a Javabean code, that is, you have started to write Javabean, then let us continue the next section.

9.2 Introduction to JavaBean Development

9.2.1 A simple JavaBean example

This section will establish a general process of beans through a simple bean constructor. Through this section, we can learn how to generate a simple bean, compile and save it to a JAR file.

1. Write the source of bean SimpleBean.java

2. Compile source program

3. Writing production (nmake) file

4. Run Makefile file

1. Write the source of bean SimpleBean.java as follows:

Import java.awt. *; import java.io.serializable;

Public class SimpleBean Extends Canvas Implements Serializable {// This bean is derived from java.awt.canvas, so it has all properties and methods of Canvas and methods public simpleBean () {setsize (60, 40); // Set the bean SETBACKGROUND Color.RED); // Setting the background color of the bean}} SimpleBean derived from the java.awt.canvas component, so it is a visualization, and implements the java.io.Serializable interface, this interface is all Beans must be implemented. , Because SimpleBean has all properties and methods of Canvas, such as background color and component size, etc., and can call the corresponding method to set these properties.

2. Compile the source program:

Javac SimpleBean.java generates a zodical code file SimpleBean.class.

3. Writing production (nmake) file

This NMAKE file compiles this SimpleBean component and generates a JAR file. Store the written makefile file as Simpe.gmk (Unix) or Simple.mk (Windows), and put your simpleBean.class in the same directory, the NMAKE file list is as follows:

#Gmumake file classfiles = SimpleBean.class jarfile = SimpleBean.jar All: $ (JARFILE) # Create a JAR file $ (JARFILE) $ (ClassFiles) Echo "Name: SimpleBean.class ">> Manifest.tmp Echo" Java-Bean: True ">> Manifest.tmp Jar CFM $ (Jarfile) Manifest.tmp * .class @ / bin / rm manifest.tmp # Compile source program% .Class: % .java export classpath; classpath =.; / javac $ <# Delete Generated Intermediate File clean: / bin / rm -f * .class / bin / rm -f $ (jarfile) # nmake file classfiles = SimpleBean.class jarfile = SimpleBean.jar All: $ (JARFILE) # Create a JAR file with the appropriate description (JARFILE) $ (ClassFiles) JAR CFM $ (Jarfile) JAR CFM $ (JARFILE)

4. Run Makefile file

For UNIX, run gnumake simple.gmk For Windows, run NMAKE -F Simple.mk to create a JAR file in the current directory, this JAR file contains this bean information.

This section we completed a typical Javabean, in fact, a Java class with certain special rules, which has some special places, such as implementing certain interface classes, but it is still a Java class, which can use any Java language The functionality provided is inherited in Canvas et al. And the Makefile we provided above can be used as a template. You only need to modify the makefile provided above when you want to write your own bean's makefile.

9.2.2 Using this JavaBean constructor application

In the previous section, we have made a Javabean, then how to use this Javabean, in this section, we will use this JavaBean in a Java applet.

1. Write SimpleBeantest.java files

2. Compile this file

3. Need to write TestBean.html files

4. View results with AppletViewer

1. Write SimpleBeantest.java files, the source program is as follows:

Import java.applet. *; public class simplebeantest extends applet {public void init () {add (new simplebean ()); // Use SimpleBean}} 2 in this applet. Compile this file as follows:

Javac SimpleBeantest.java

3. You also need to write TestBean.html files, the source program is as follows:

4. Use the AppletViewer to view the results as follows:

AppletViewer TestBean.html

If you see the results shown below, it is obvious that you have successfully applied your bean to this applet. If the result is not coming out, don't worry, see if all of your files are all under a directory.

This section we use Beans to an applet, you start feeling the power of Bean, if we have a lot of beans, then build applications is very convenient, just need to use different beans according to different features, And we only need to build a framework of the application, which looks like a homework game of childhood. 9.2.3 Introduction to the Development Tool of Javabean

If you have used Visual Basic or Delphi, you will feel that a good integrated development environment can bring great convenience to programmers. We won't feel trouble when writing simple beans, but if we need to develop beans with complex structures, a good integrated development environment will be easier to make our work. Fortunately, we not only have a lot of beans that can be used, but there are many BEAN development tools available. Here we focus on several common bean development tools.

1. Borland's JBuilder

2. IBM's Visual Age for Java

3. Sunsoft's Java Studio 1. Borland's JBuilder

Using JBuilder, developers can use any JavaBean components included in this product or from third-party vendors to quickly develop applications, or use JBuilder's visual design tools and Wizard to create their own yours. Javabean. Component. JBuilder contains powerful JavaBean database components that meet the needs of the application related to the database. In addition, JBuilder provides a Java optimization toolset to provide comprehensive, high-performance development solutions for professional Java developers. JBuilder's component development environment, including component designers and bidirectional tool engines, is built in Java using JavaBean.

About JBuilder more information, you can visit Borland's Web Site: http://www.borland.com/JBuilder

2. IBM's Visual Age for Java

IBM's Visual Age for Java's release makes the implementation of the Internet application of the client / server system becomes a reality. This tool combines Java's rapid development environment with visual programming. Visual Age for Java is a programming environment that creates an application, applet, and Javabean components that make developers can focus on the logic design of the application. Visual Age for Java can help developers implement the tasks that often need in many applications, such as communication code, perform web connection on the enterprise level, and creation of user interface code.

More detailed information about Visual Age for Java can be viewed from the Web site: http://www.software.ibm.com/ad/vajava3. Sunsoft's Java Studio

Java Studio is a visual assembly tool, a "ready" HTML creation tool and a reusable component development tool that is fully used by Java. Java Studio uses JavaBean technology that includes a rich and strong business component set, including charts, curves, and database access and operations supported by forms and spreadsheets. In addition, it is also included to create a network software auxiliary component. Auxiliary components include spreadsheets, whiteboards and chat components.

Java Studio's Web URL is located at http://www.sun.com/studio/

This section describes several commonly used JavaBean integrated development environments, but in fact, their functions are very powerful, in fact, they are all Java integrated development environments, but also build JavaBean, but also build applications related to Java and applets, etc. Java-related products, you may wish to see which development environment is more suitable for you, of course, if you think that use UltraEdit JDK to develop Java programs is a very happy thing, then you can't pay attention to these huge integrated development environments. 9.2.4 Using Beanbox Test Javabean

BDK (Beans Developmen Kit) is a Beans Development Toolbox issued by Sun, which is used in conjunction with JDK, which can generate Beans using a bean event model. The use of BDK is dependent on JDK. Beanbox is a tool for testing Beans in BDK to manage Beans properties and events. Beanbox is not a tool to build Beans. It is just a test tool, we can learn Beans.

In the installation directory of the BDK, there is a subdirectory beanbox. There is a beanbox executable in this directory, running run.sh under the UNIX platform, running run.bat under the Windows platform, you can start the BeanBox application.

After starting BeanBox, three windows appear: Toolbox window (left), beanbox window (middle) and property editing window (right), as shown:

The Toolbox window contains Beans that can be used in Beanbox. You can choose the required bean from the window, drag and drop it to the Beanbox window. The Beanbox window can be used to touch each bean, defining the appearance of beans, how to interact with other beans. The Beanbox window itself is an instance of Beanbox this bean. In order to put a bean in the Beanbox window, select a bean from the bean icon or name of the Toolbox window, then click the mouse in the center you want to place in Bean to place the bean in the Beanbox window, then Bean will be in the specified location display. To select one from several beans, just click on the bean with a mouse. The selected bean will have a black and white border.

The property editing window displays the properties of the currently selected bean, or you can modify the properties of the bean in this window. Below we use beanbox to test the SimpleBean we have completed in front of us.

1. Load the JAR file into Toolbox. Select Menu Item File | Loadjar, one file selection box will appear. Look for the location of simpleBean.jar, then select the file, then SimpleBean will appear at the bottom of Toolbox (all Beans contained in the JARS subdirectory in the JARS subdirectory of the BDK in the directory of the BDK will automatically load Toolbox. ). 2. Select an instance of SimpleBean to the Beanbox container. Click the SimpleBean option with the mouse in Toolbox. This is the mouse will change to a cross-shaped, and the mouse is pressed in the Beanbox window, and the SimpleBean will appear in a color rectangular frame with a shadow wire. The border indicates that SimpleBean is selected, and the properties of SimpleBeans will appear in the Properties editing window. Since SimpleBean is derived from Canvas, you can change the size and location as normal components.

3. Checking SimpleBean properties and events show the current bean properties in the Properties Editing window. When you select SimpleBean, 4 properties will be displayed: foreground color, background color, font, name. We didn't display attributes in the SimpleBean, which inherited from Canvas. You will pop up a property editing dialog box at each attribute. The properties can be modified in the Properties Editing dialog box.

Beans communicate with other beans by sending and receiving events. In order to learn which types of events can be sent, you can select the Edit | Event menu item. An event list will appear, which is the type of event that the bean can send.

Beanbox loaded by Beanbox is a standard JavaBean. Beanbox can edit the JavaBean properties. You can also edit the event between JavaBean, so that different JavaBean works, and beanbox is small, it is very convenient. Tools, we can use Beanbox to verify that the JavaBean we have written is in line with the specification. 9.3 Basic Concepts and Programming of RMI

9.3.1 Basic Concept of RMI

Java RMI (Remote Method Invocation) - The remote method of Java is a distributed computing technology unique to Java, which allows the object to be run on a Java virtual machine to call the object of the object on another Java virtual machine, thus Enables Java programmers to easily distribute them in a network environment. Object-oriented design requires that each task is performed by an object that is best for this task, and the RMI deepens this concept in a step, enabling tasks to be done on the machine that is best suited for this task.

RMI defines a set of remote interfaces to generate remote objects. The client can call the remote object with the same syntax like the same syntax as the method of calling the local object. The classes and methods provided by the RMI API can process serialization required for all access communication and parameter reference requirements for accessing remote methods.

Remote method calls similar to the remote process call (RPC) feature proposed by Sun's 1985. RPC also requires serialization parameters and returns numerical data, but because there is no object involved, the situation is relatively simple. Sun has developed an external data representation (XDR) system that supports data serialization. An important difference between RPC and RMI is that RPC uses fast and insufficient UDP protocols, RMI with low-speed and reliable TCP / IP protocol.

Remote Method Call (RMI) and CORBA are all distributed computing technologies, and there is a disadvantage in the distribution, in order to help understand the features and use of RMI, it is necessary to discuss the difference between CORBA and RMI.

Corba (Common Object Request Broker Architecture) is an Object Management Architecture (Object Management Structure) of OMG, which is a standard for object-oriented distributed system. CORBA is designed to be an open instructions that can be used in all programming languages, that is, Java customers on a machine can request another machine service with SmallTalk or C . It is because the independence of this language makes Corba so flexible and attractive. In order to adapt to language independence, CORBA uses very common standards as its interface. In different languages, remote calls, signatures, and objects have their own different definitions, so CORBA must be as neutral and open. It is this versatility that is a weakness of CORBA. When developers use CORBA, they have to use a new standard definition language interface, which requires developers to learn new programming interfaces, thereby reducing transparency of the remote model. RMI is developed for Java's distributed computing in Java. The standard for remote call is developed for Java and application Java's natural Java signature and call, which makes RMI relatively transparent to Java developers and is easy to implement. RMI is closely integrated with Java language to provide very good fault tolerance compared to CORBA and to abnormally. Although Java's RMI standard is not as independent like CORBA, Java itself is a stand-alone platform, which makes RMI a good choice in cross-platform distribution software development.

RMI is the basic model of Java language in distributed computing, many Java distributed systems, including our EJBs, which are involved in RMI, is built in RMI. 9.3.2 General Structure of RMI System

The RMI system includes 3 floors, a stubs / frame layer (Remote Reference Layer), Transport, as shown in the figure:

When the client calls the remote method, the request is requested with the client's end call. The client references the end as the representative of the object on the remote machine. All basic functions shown above can not be seen on the client. The end code is born by the RMIC compiler, and the method call request is passed to the server object with a remote reference layer (RRL).

1) End head is the client representative of the remote object to define all the interfaces supported by the remote object version. The terminal running on the client like a local object, from the client to look similar to the local object, it also maintains the connection with the server object. The remote application layer of the client returns the transfer stream of the end. The client's RRL communicates with the RRL of the server. The end will serialize the parameter data to transfer the serialized data to the mobilization stream. After performing a long way to call, the RRL returns the serial return value back to the end and is responsible for reverse serialization.

2) The frame (Skeleton) frame is a server partner with the server RRL interface. The framework accepts the client RRL method call request. Server side RRLs need to be reversed to send any variables to the remote method. Then the frame calls the actual object of the server side. The framework is also responsible for receiving the return value from the remote object and mobilizing it into the mobilizing stream.

3) Remote Reference Layer Remote Reference Remote Reference Layer (RRL) is responsible for maintaining an independent application protocol that is not associated with specific end or framework models. This flexibility makes the change in RRL do not affect the additional two floors. RRL involves a low-level transfer interface, which is responsible for providing streams to the end and frame layers.

RRL communicates with the server partner by the transfer layer. The client side component contains specific information about the remote server. This information is passed to the server component, so it only depends on the service party RRL. Server RRL is responsible for citing grammar and managing these syntax to send remote method calls to the framework. The communication between the client and the server member component is processed by the transfer layer. 4) Transport Layer Transmission Layer is responsible for establishing and maintaining connections between clients and servers. The transfer layer includes four abstraction: Endpoint abstraction is used to reference an address space including a Java virtual machine, which is a reference to the specific transfer interface. Channel abstraction is a passage between two address spaces. This passage is responsible for managing various connections between clients and servers. Connection Abbreviation is an abstraction of data transfer between clients and servers. Transport abstraction is responsible for establishing channels between local address spaces and remote endpoints. Transfer abstraction is also responsible for receiving an input connection that contains an abstract address space. The transfer layer establishes a connection to manage the remote object in the existing connection and processing address space. When the transfer layer receives the client side RRL request, it looks for the RMI server of the requested remote object, and then the transfer layer is established to this server's plug connection. Next, the transfer layer passes the established connection to the client RRL and adds a reference to the remote object to the internal table. At this time, the client is connected to the server. Transmit layer monitors "activity" of the connection. If there is no movement after a longer period of connection, the transfer layer is responsible for turning off this connection. The hierarchical structure of RMI is not only conceptual and reasonable, but also provides us to develop RMI applications to provide great convenience, imagine that if we need to understand the details of the transfer layer, then RMI application Development will be a very difficult task. Fortunately, we don't have to do it. RMI's hierarchical structure is that we can develop in the high-level, do not necessarily understand the details of the underlying, in fact, there is almost no difference in developing RMI applications and developing normal Java applications.

9.3.3 Construct distributed application system using RMI

RMI applications are usually composed of two separate programs: a Server and a client. A typical Server application creates some remote objects to be referenced, and waits for the client to call the method of these remote objects. A typical Client application gets a remote reference for one or more remote objects on the Server, and calls the methods of these objects. RMI provides mechanism for Server and Client communication and delivery information. Such an application is called a distributed object application.

Distributed object applications require location remote objects: applications can use one of two mechanisms to get references to remote objects. The application can use the RMI naming tool RMIREGISTRY to register its remote object, or transmit and return a reference to the remote object as in general operation.

And remote object communication: Communication details between remote objects are processed by RMI. For programmers, remote communication is like a standard Java method called. Loading the class by-code code that is transmitted: Because the RMI allows the caller to pass objects to remote objects, it provides the necessary mechanisms that deliver data and load an object code.

The figure below describes a RMI distributed application that uses a registration mechanism to get a remote object reference. The Server Call registrar links a remote object and a name. The Client party looks for remote objects through the name in the registrar in Server. The figure also shows that the RMI system uses an existing web server to load the class bytecode, and transmits the bytecode between Server and Client when needed.

An important and unique feature of RMI is that it can dynamically download the bytecode (or simple code) of an object class that is not defined in the recipient's virtual machine. The type and behavior of an object, which can only be available in a single virtual machine, which can be passed to the other may be a remote virtual machine. RMI communicates the object along with its true type, so behavior does not change when these objects are passed to another virtual machine. This allows new types to introduce a remote virtual machine to dynamically expand an application's behavior. Like other applications, a distributed application using Java RMI is also consisting of interfaces and classes. In the interface define some methods, classes defined in the interface, and define some other methods. In a distributed application, some implementations require resident on different virtual machines. Objects with methods that can be modified across the virtual machine called remote objects. An object is a remote object by implementing a remote interface, which has the following characteristics:

1) A remote interface is derived from java.rmi.Remote.

2) Each method in the interface must declare the java.rmi.RemoteException, except for other special exceptions. When the object is passed from a virtual machine to another virtual machine, the RMI is different from the non-remote object. For remote objects, the RMI passes a remote end of the recipient virtual machine, not a copy of an object. The end as a local identification or agent of the remote object, is a remote reference for the caller. The call party calls a method of local end, which is responsible for processing method calls for remote objects by local ends.

The end of a remote object implements the same interface as the remote object. This allows one end to be converted to any of the interfaces implemented by the remote object. This also means that only methods defined in the remote interface can be called on the recipient virtual machine.

When you use RMI to develop a distributed application, you need to follow the steps below:

1) Design and implement your distributed application components. First, determine the structure of the application, which components are local objects, which should be remotely accessed. This step includes:

Define Remote Interface: A remote interface defines a method that can be remotely called by the client. The client programming remote interface instead of a class that implements these interfaces. A part of the design of such an interface depends on the local object as the parameters of these methods and the return value. If there is no such interface and class existence, you need yourself to be defined.

Implement a remote object: Remote objects must implement one or more remote interfaces. Remote object classes may include other interfaces (local or remote) and methods (only available locally). If there is a local class as a parameter or return value of these methods, these classes must also be implemented. Implement the client: Users using the remote object can be implemented at any time after the remote interface is defined, including the remote object being expanded.

2) Compile the source program and generate the end. This is a two-step operation process. The first step is to compile the source file using the Javac compiler, which contains a remote interface and its implementation part, a Server class, and a Client class. In the second step, use the RMIC compiler to generate the end of the remote object. RMI uses a remote object's end class as a client's agent, allowing the client to communicate with the same specific remote object.

3) Make the class can be accessed through the network. This step makes everything related to the remote interface, end, and other classes that need to download to the client party via a Web Server access.

4) Start the application. The launch application includes running the RMI Remote Object Registration Program, Server, and Client.

Is it very simple to construct a distributed application system with RMI? Indeed, RMI allows us to write a distributed application, which is difficult to imagine before the RMI.

9.3.4 Example of a simple RMI

An example of a simple but complete RMI distributed application, the program consists of two parts; the Server party including the remote object and the remote method of calling the Server party SayHello () get the string "Hello World" and output the string Client. 1. Construct a remote interface Hello

2. Complete the Server program, define the HelloIMPL class to implement the Hello interface

3. Complete the Client program

1. Construct a remote interface Hello:

Package Hello; Public Interface Hello Extends Java.rmi.Remote {// RMI application must inherit since Java.rmi.Remote string SayHello () throws java.rmi.RemoteException; // Define Interface to remotely call}

2. Complete the Server program, define the HelloIMPL class to implement the Hello interface:

package hello; import java.rmi *;. import java.rmi.server.UnicastRemoteObject; public class HelloImpl extends UnicastRemoteObject implements Hello // implement the interface Hello {private String name; public HelloImpl (String s) throws java.rmi.RemoteException {super (); // call the parent class constructor Name = S;} public string Sayhello () throws remoteexception {return "Hello World!"; // Implement the method of Hello interface definition} public static void main (String args []) {System.SetSecurityManager ()); // Setting the security policy required by the RMI program try {helloimpl obj = new helloimpl ("HelloServer"); // Generate an instance of HelloImpl Naming.Rebind ("HelloServer", OBJ) ; // Bind this instance to a name system.out.println ("HelloImpl Created and Bound In the Registry to the name HelloServer);} catch (exception e) {system.out.println (" HelloImpl.main : an Exception Occured: "); E.PrintStackTrace (); // If an exception is generated, the error message is printed}}}}}}}}}}}}

The Server party generates a remote object and binds with a name "HelloServer" with the customer-talk. The Client end can look for the corresponding remote object according to the name, and then call its remote method.

3. Complete the Client program

package hello; import java.rmi *;. public class HelloClient {public static void main (String args []) {System.setSecurityManager (new RMISecurityManager ()); // set the security policy required RMI try {Hello obj = (Hello Naming.lookup ("HelloServer"); // Get a Hello from the server string message = obj.SAYHELLO (); // Remote call Hello method system.out.println (message); // will output Result Print} Catch (Exception E) {System.out.Println ("Hello Client: An Exception Occured); E.PrintStackTrace (); // If there is an abnormality, output exception information}}} Client uses Java.RMI package The Naming class lookup () method obtains a remote object OBJ, then calls its remote method SayHello () to obtain the string "Hello World" and output it on the screen.

To run these programs, there are some work to do, these programs are named Hello.java, HelloImpl.java, HelloClient.java, they are placed in D: / Hello directory, in Windows Next, you need to run them in the command window:

1. Set classpath =% classpath%; D: /

2. Compile the source code under D: / Hello: javac -d .. * .java

3. In generating the end and frame module, first switch back to D: / rmic -d. Hello.HelloImpl

4. Run the RMI Remote Object Registration Program in D: / Under

5. Running server program java -djava.security hello.policy = my.policy hello.policy = my.policy helli.HelloIMPL

6. Run client program java -djava.security.policy = my.policy hellino = my.policy hello.helloclient

The above steps in the steps of 5 and 6 is a file, this file and Java security mechanism, we do not need security restrictions in this program, so we can access the permissions to all access. My.Policy is as follows: Grant {Permission java.security.Allpermission;};

You must remember to set this file, otherwise the RMI will "reject access" errors. If you want to know other secure mechanisms of Java, you can refer to the information about Security in Java.

RMI belongs to the Java advanced technology. Through this section, you should have a certain understanding of RMI, distributed calculation is a very important technology, and Java has a good prospect in distributed computing. Based on RMI, Java will have a large as a distributed calculation.

9.4 EJB Introduction

9.4.1 EJB background

The emergence of EJB is a great driving of Java technology because EJB is mainly for enterprise applications, which makes Java have the direction of enterprise applications. Similarly, EJB is also built on Java language, like JavaBean, Java Applet, is also complied with a certain normative Java program, but this is a complex specification. Traditional distributed applications are based on Client / Server structures, and in recent years, people have found a lot of shortcomings based on Client / Server architecture, such as: If the client's code needs to change, then client programs on all machines To reinstall; if a machine has a non-fixed damage, then you have to reinstall the client software on other machines to be used. BROWSER / SERVER-based applications do not have more shortcomings, we can use any browser machines to work, because all program logic is on the server, so the server-side code changes do not need to be used as customers. Did the browser does anything again.

Due to these advantages of the Browser / Server structure, there have been many research and practices in recent years on Browser / Server program development model. Because Browser has no way to indicate complex program logic, there must be a layer between the Browser and Storage Media Database indicating the interface, which is responsible for complex program logic. This is what we said, in the Brower / Server structure, our job is to develop server-side components, but develop server-side components is very troublesome. Because the server-side component must accept a number of client requests, it must have multi-threaded and transaction processing, and these are also difficult for server-side components development.

At the Javaone98 developer conference held in San Francisco, SUN officially issued an industry-based EJB1.0 (Enterprise Javabean 1.0) specification description, which has caused huge reactions in many large companies and developers. This marks the use of Java development server-side components and construction enterprise-level applications will become simpler. Now the EJB2.0 version has been released, and the corresponding EJB products have nowcent, like WebLogic WebLogic, IBM's WebSphere, Inprise's Inprise Application Server, etc., is a successful product. 9.4.2 Overview of EJB

In fact, EJB is a norm of Java in an enterprise application. Therefore, EJB is more complicated. EJB is just a component of the component, and in order to let EJB run up, there are many other things, such as containers, application servers, etc., these are And EJB is closely linked, because EJB is generally used in web applications, so you need a web server, and EJB client can also be any Java program, such as applet, servlet, etc., so EJB is just enterprise level. Part of the application platform, and this enterprise-level application platform is Sun's J2EE (Java 2 Enterprise Edition). And WebLogic we mentioned above, WebSphere is actually in line with J2EE's enterprise application platform.

The EJB specification description defines the Java server-side component model. There are currently available, those provided by third-party vendors, those used for client-side components, but not much components for server-side, due to server-side components It is very lacking or difficult to construct, so basically every developer has to construct a server architecture from the beginning, which is a very bad result. The emergence of EJB is exactly to solve this problem. The EJB method expands the Java client component model JavaBeans and the development of server-side application systems. In the EJB specification description, many of the functions in the server are provided by EJB containers, and developers can concentrate. Efficient on the core function of the application system. The use of EJB technology can greatly reduce the workload of the development server-side application system, so the EJB specification description will immediately cause great interest in developers. The definition of EJB in the document released by Sun is: EJB is a component architecture for developing and deploying multi-layer structures, distributed, object-oriented Java application systems. Adopting EJB can make the development commercial application make it easy, the application system can develop in a support for EJB, and deploy in other EJB environments after development, with the changes in the demand, the application system can not modify the migration to Other functions, more complex servers.

EJB simplifies the development process of multi-layer architecture application system. In the development of a distributed application system, there are many advantages in the method of multi-layer architecture, such as increasing scalability, reliability, flexibility, etc. of the application system. Because the server-side component can be modified according to application requirements, and the component is not related to the location and application in the network, the system administrator can easily reconfigure the system's load. Multi-layer architecture is ideal for business transaction systems for large data volume, especially in web-based applications, requires multi-layer architecture to support fast applet downloads of thin clients and browsers, and more and more systems are beginning to start Multi-layer architecture method, so-called multi-layer structure, you can use the following figure to help understand:

In multi-layer structures, the database is a layer, and the client has a layer, and the client and database are collectively referred to as N-2 floors, and the N-2 layer is mainly the logic of the program. The role of EJB is to represent the logic of the program and provide an interface to access the database in this N-2 layer. EJB is divided into two categories, one is entity bean (entity bean), which has a corresponding relationship in this EJB and database, which can automatically update the content in the table when data changes. Another category is a dialogue bean. This EJB is used to interact with the client, representing the logic of the program, we can use these two EJBs to easily build your own multi-layer system.

EJB refers to a new height of Java's "Write Once, Run Anywhere", and the server-side component is executed within the component execution system, the specification means defines the services required by the component execution system, and the components that are developed in accordance with the EJB specification Any system that supports EJB. EJB is actually executed in the container. Sun also releases the specification of the EJB container. EJB can run in any compliant container. The container is actually serving EJB, such as EJB needs transaction, multi-threading and Security mechanism and other services. 9.4.3 Introduction to the soft component model of EJB

JavaBean is also a component, but it is not a component of the server. In the component, we call JavaBean lightweight, and EJB is heavyweight. If you want to know about some components, you can refer to the books and information on the components.

The idea of ​​the soft member model is to create reusable components and combine it into the container to obtain a new application system, the component model defines the basic architecture of the component, the structure interface structure, and the mechanism of other components and containers interaction, etc. . With the specifications of the component model, component developers develop components that implement the application logic, while application system developers combine these pre-developed components into an application system, which can also be used as new components. Soft build model ideas have been quickly popular in the software development community, as it can reach these purposes: reuse, high-level development, automated development, simplifying development processes, etc. JavaBeans, EJB, COM / DCOM, etc. are examples of soft components models. There are two types of soft component models - client components and server-side component models. The client component model such as JavaBeans is specifically designed for handlers and user interface issues; server-side component models, such as EJB, providing infrastructure to middleware-oriented middleware.

The server-side component model links the development and middleware of the component model. Enterprise-level intermediates are known for their complexity, but it refers not only to application logic, concurrency, and scalability issues, but also to how to combine incompatible systems together. The server-side component model solves the complexity problem of middleware development, which makes the middleware developers focus on the logical part of the application system without handling synchronous, scalability, transaction integration, network, distributed object framework, etc. Complicated complex issues in the application system. The EJB component model is shown below:

The EJB component model provides developers with support: 1. The component contains application logic 2. Reusable member 3. Scalability 4. Resource management 5. Business support 6. Concurrency management

These support for the developers of the server-side components provide a great convenience, making the development server-side components no longer a very difficult task. 9.4.4 Relationship between EJB and other technologies

1. EJB and JavaBean relationship

2. Relationship between EJB and RMI

3. EJB and network calculation relationship

1. EJB and JavaBean relationship

Many people often confuse JavaBean and EJB, JavaBean provides components based on component development mechanisms, general Javabeans are visual components, and some Javabeans are non-visual, JavaBeans can be reused in multiple applications, a standard JavaBeans is a customer The end member cannot be accessed or operated by other client programs at runtime, but the client's JavaBeans container can operate on JavaBeans according to the design or runtime definition of JavaBeans, and JavaBeans is not necessarily used for Client. System of / Server structure.

EJB does not have a user interface, fully in the server side, EJB can make multiple JavaBeans, specification descriptions Detailed description of the demand that EJB containers need to meet and how to collaborate with EJB components. EJB can communicate with the remote client program, and provide a certain function. According to the specification, EJB is part of the Client / Server system, if not interacting with the client program, EJB generally does not perform specific functions. An important difference between EJB and JavaBean is that EJB provides network features.

2. Relationship between EJB and RMI

EJB is a distributed component that supports remote calls. The EJB's network features are built on RMI, which can be said that RMI is the cornerstone of EJB network characteristics.

Because EJB is distributed, how to locate an EJB is also a problem that needs to be resolved, and this problem is the same as the RMI, and EJB also uses RMI Registry's idea, EJB JAVI (Java Naming and Directory) Interface also provides a service that registers an object, and the object that has been registered can be easily found. This is the same as the idea and functionality of RMI's Registry. The more you go deep into EJB, you will see the shadow of the RMI. 3. EJB and network calculation relationship

Applications constructed from Beans can decompose into different components based on the user's needs, provide related components according to the functionality required by the user, and download new components at any time as the user's new needs, and the user does not use its function. The component can reside on the server, which is the concept of network calculation.

Many people do not fully understand the Java concept, they think that in order to run Java programs on a client, they need to transfer a huge, possible Java application that can reach a few megabytes, in fact, This is also a mistake when developers plan to use Java to change old application systems.

The best way to utilize Java in the network computing environment is a component of the EJB to provide the server, and by JavaBeans provide the client's components, both combined, will make the application system more simple and fast.

Only use Java applications to server-side applications to truly embody the power of Java, EJB is the Java server-side component model, which guarantees that the developed component can be deployed in any system that supports EJB specification, making the system both Provided by different developers. Adopting EJB can improve the productivity of developers, component developers and application developers do not need to implement some of the complex logical structures in the system, because the components' container has provided automatic management and control of these services, using EJB development application systems Modifications You can migrate from one server to another more than a stronger server.

In summary, EJB technology will enable Java to strengthen the status of enterprise calculations, providing a framework based on Java-based applications, and EJB has many superiority compared to many systems and models, indicating that EJB is possible. The primary choice for server-side component models for distributed applications.

[本 讲 小]

This lecture mainly explains two branches of Java technology: one is component technology, which mainly involves JavaBean technology, also introduces the currently popular EJB technology; one is a distributed calculation technology, mainly involved RMI technology. Both branches are the advanced features of the Java language, which is developed on the basis of Java language.

Since these advanced technologies involve knowledge other than Java languages, JavaBean involves the knowledge of component technology, RMI involves distributed computing knowledge, so it is more difficult to understand, although Java language is very easy to use, So the technique built on it will also have easy-to-use features, but it still takes a period of time learning. Especially the EJB involved in this lecture, this is a new technique that is strong and complex, which requires a lot of incidents, and makes a lot of practice to truly master.

To master these advanced technologies of Java, the most basic concept is clear, and the concept is slowly cultivated in practice, so you still have to practice, I believe that you will have new gains after every exercise, for questions The understanding will become more and more deeper, and there is more and more opinions. This is not just learning Java, but also the only way to learn other technologies.

转载请注明原文地址:https://www.9cbs.com/read-21116.html

New Post(0)