Java Bean introduction and application

Source: Internet
Author: User

Java Bean introduction and application
The Chinese meaning of Bean is "Bean". As the name suggests, JavaBean is a Java applet. JavaBean actually refers to a special Java class. It is usually used to implement some common simple functions and can be easily reused or inserted into other applications. All Java classes that follow certain programming principles can be called JavaBean.

 

1. Java Bean technology Overview

Java Bean is a Java-based component model that consists of three parts: attributes, methods, and events. In this model, JavaBean can be modified or combined with other components to generate new components or complete programs. It is a Java class that is encapsulated into objects with certain functions or processing a business. Therefore, you can also access the Bean and its attributes through the Java code embedded in the JSP page.

Bean indicates a Java component that can be reused. A component is a group composed of one or more classes that can be internally managed by itself, and the outside world does not know its internal information and operation methods. Objects that use it can only be operated through interfaces.

Ii. Java Bean compiling specifications

Java Bean is actually a Java class written according to the Bean Naming and Design Specifications specified by the JavaBean technical standard. These classes follow an Interface format to facilitate function naming, underlying behavior, and inheritance or implementation behavior. The biggest advantage of these classes is that they can implement code reusability. Bean does not need to inherit Special Base classes (BaseClass) or implement specific interfaces ). Bean compiling specifications enable the Bean Container (Container) to analyze a Java class file and translate its method (Methods) into Properties ), java class is used as a Bean class. Bean compiling rules include Bean class constructor, defining attributes, and accessing method compiling rules.

 

2.1. Bean Component Working Mechanism

Five important mechanisms for this component are defined in the JavaBeansVersion1.01 A specification:

(1)Introspection ):Create an object library that can be reused in other components, such as user permission control and automatic email reply.

(2)Communication ):Generates and collects Component Message events.

(3)Persistence ):The status of the component.

(4)Properties ):Controls the layout of components, including space occupied by components and relative positions of components.

(5)Customization ):Developers can control the change mechanism required by components.

 

2.2. Java Bean writing requirements

Compiling a JavaBean must meet the following requirements:

(1) All the JavaBean must be placed in a Package.

(2) JavaBean must generate a public class, and the file name should be consistent with the class name.

(3) All attributes must be encapsulated. A JavaBean class should not have public instance variables, and all class variables are private.

(4) attribute values should be accessed through a set of access methods (getXxx and setXxx): For each attribute, there should be a dedicated instance variable that matches the public getter and setter methods.

(5) The Java Bean class must have an empty constructor: the class must have a public constructor without parameters, this constructor should also call the setting methods of each attribute to set the default value of the attribute.

 

2.3. Java Bean naming rules

Java Bean naming rules are as follows:

(1) package name: All letters are in lower case.

(2) Class naming: the first letter of each word is capitalized.

(3) attribute name: The first word is in lowercase, and then the first letter of each word is in uppercase.

(4) method name: Same as the attribute naming method.

(5) constant name: all uppercase letters.

 

2.4. Java Bean package

The package is the package. The package of JavaBean is basically the same as the package described in the previous chapter, but there are also differences. The packages described above are defined in Java, the JavaBean package is customized by the user.

After each JavaBean source file is compiled into a. class file, it must be stored in the corresponding folder. The folder for storing this. class file is a package. The an package must be stored in a specific directory. Each JSP Engine specifies the location where the JavaBean package is stored. Different JSP engines have different requirements on the location where the JavaBean package is stored, for example, in Tomcat, all the an packages are stored in the WEB-INF/classes folder. If a multi-level directory exists, you need to include all the upper-level directories in the directory where the. class file is located in the package name. Each level of directory is separated by a comma. Example code: packagejsp. example. mybean;

 

2.5. Structure of Java Bean

(1) attribute: A member variable of the Java Bean class, used to describe the status of the JavaBean object. An event is triggered when the object property value changes. The attribute itself is the event source.

(2) method: in Java Bean, functions and procedures are collectively referred to as methods. You can use methods to change and obtain attribute values. Methods can be divided into constructor methods, access methods, and common methods.

(3) Event: an event is actually a special Java Bean. An event is triggered when the attribute value changes. An event inspires the relevant object to respond, java Bean registers the object event listener mechanism to receive and process events. It implements communication between Java Beans.

 

Iii. Java Bean attributes

In the previous section, we briefly mentioned the attributes of JavaBean, the attributes of Java Bean and the attributes referred to in general Java programs, in other words, the object attributes in all object-oriented programming languages are a concept. The specific embodiment of the program is the variables in the class. There are four types of attributes:Single value (Simple), Index, association, and constraint)Attribute. This section describes these attributes in detail.

 

3.1. Single value (simple) Attribute

A single value (Simple) attribute is the most common attribute type. This type of attribute has only one single data value. The data type of this data value can be any data type in Java, including classes and interfaces.

Attributes are defined and corresponding access methods need to be defined. Generally, each single-value attribute is accompanied by a pair of get/set methods. The property name corresponds to the get/set method name related to the property. For example, if there is an attribute named "xxx", there will be the setXxx and getXxx methods.

In addition, the Boolean attribute is a special single-Value Attribute. It has only two allowed values: true and false. If there is a Boolean attribute named "xxx, then you can access it through the isX method.

 

3.2. Index attributes

If you need to define a batch of attributes of the same type, it will be very cumbersome to use the single-Value Attribute. To solve this problem, JavaBean provides the index attribute, the index attribute is a member variable of the array type in the JavaBean. Use the set/get method corresponding to this attribute to obtain the value of the array. You can set an index attribute or obtain the value of an element in the attribute through the corresponding access method. You can also set or obtain the value of the entire attribute at one time.

 

3.3. Association (Bound) attributes

The Association attribute refers to other objects to be notified when the value of this attribute changes. Each time the attribute value changes, this property triggers a PropertyChange event (in a Java program, the event is also an object ). The event encapsulates the attribute name, the original value of the attribute, and the new value after the attribute changes. When such an event is passed to other Beans, it is defined by the Beans that receive the event.

Attribute change is called a JavaBean event. Class objects related to events such as Java Bean are called listeners ). The listener may only be interested in a property-related event of the JavaBean or all property-related events. Therefore, the JavaBean provides two types of event listener registration and cancellation methods:Registration and cancellation of Global Event ListenersAndGeneral event listener registration and cancellation Methods.

 

3.4. Constraints attributes

When the attributes of Java Bean are changed, the related external class object should first check the rationality of the attribute change and then decide whether to accept the change. Such a JavaBean attribute is called a Constrained attribute. When the change of the constraint attribute is rejected, the method for changing the constraint attribute produces a PropertyVetoException. With this exception, the JavaBean constraint attribute is restored to the original value, A new attribute modification notification is sent for this restoration operation.

The change of the constraint attribute may be rejected, so its setXxx is also different from the setXxx of other JavaBean attributes. Write constraints as follows:

Public void setXxx (xxxType newXxx) throws PropertyVetoException

 

Iv. Java Bean Method

4.1. Constructor

The constructor of Java Bean is the same as the constructor of common java classes. It initializes the attributes and methods of JavaBean, that is, set an initial value for the defined attributes and methods. The constructor name must be the same as the class name of the JavaBean.

 

4.2. Access Method

After defining Bean attributes and initializing them through constructor, you must create an access method for other programs to access these attributes of Bean. The access method is the access to the attributes defined in the component, including the read and write access methods. Read is a value function used to retrieve the value of the Bean attribute, that isGetterWrite is a value assignment function used to set Bean properties, that isSetter. The following lists the syntax formats of Bean attribute access methods:

Public void setPropertyName (PropertyTypevalue); // assign a value to the attribute, that is, the write method.

Public PropertyType getPropertyName (); // read the attribute value, that is, the read Method

 

4.3. General Method

In addition to the attribute access method, you can also create a general method in Bean to call the function, as long as the general method in Bean is defined as a public method, can be called by other programs.

 

5. Java Bean events

Event processing is the core of the JavaBeans architecture. Through the event processing mechanism, some components can be used as the event source to issue events that can be received by the descriptive environment or other components. In this way, different components can be combined in the constructor, and components communicate with each other through event transmission to form an application. In terms of concept, an event is a transmission mechanism in which a certain state changes between the "source object" and "listener object. Events have many different purposes, such as mouse events, window boundary change events, and keyboard events that are often handled in Windows.

 

5.1. event model

Java Bean event model. The event source is a JavaBean class object that transmits the time object of attribute change to the event listener. The event listener is responsible for event processing. The event listener must be registered with the event source.

 

5.2. Event status object

The status information related to the event is generally encapsulated in the event status object.(EventState Object)This object is a subclass of java. util. EventObject. According to design habits, the name of this Event state object class should end with Event. For example, the Code is an example of moving an event with a mouse.

 

5.3. Event listener interface and event listener

Because the Java event model is called based on methods, you need to define and organize event manipulation methods.In JavaBeans, event manipulation methods are defined in the event listener (EventListener) interface that inherits the java. util. EventListener class.According to the regulations, the name of the EventListener interface should end with Listener. To manipulate any class in the EventListener interface, the defined methods must be implemented in this interface. This class is the event listener. For example, the following code:

// Define a mouse moving event object first

Public class MouseMovedExampleEventextends java. util. EventObject {

// This class contains the status information related to the mouse movement event

...

}

// Defines the listener interface for mouse movement events

Interface MouseMovedExampleListener extends java. util. EventListener {

// Defines the methods supported by the mouse movement event listener in this interface

Void mouseMoved (MouseMovedExampleEvent mme );

}

 

5.4 event listener registration and cancellation

In order for various possible event listeners to register themselves into an appropriate event source, the event stream between the source and the event listener is established. The event source must provide the event listener with registration and cancellation methods. In practice, the registration and cancellation of Event Listeners should use the following standard design format:

Public void add (<ListenerType> listener );

Public void remove (<ListenerType> listener );

The following is a specific example. First, an event listener interface is defined:

Import java. util .*;

Public interface ModelChangedListenerextends EventListener

{Void modelChanged (EventObjecte );}

 

5.5. Adaption class

Adaptation classes are an extremely important part of the Java event model. In some application scenariosBetween source and listenerThe transfer must be "forwarded" through the Adaptation class ". For example, when the event SOURCE sends an event, and several event listening objects can receive the event, but only the specified object responds to the event, you need to insert an event adapter class between the event source and the event listener to specify which listeners should respond to the event. The adaptation class becomes the event listener. The event source actually registers the adaptation class as the listener into the listener queue, but the real event responder is not in the listener queue, the action that the event responder should do is determined by the adaptation class. Currently, most development tools use adaptive classes to process events when generating code.

 

6. Application of Java Bean in JSP

We have learned how to write Java Bean before. Because the Java Bean is used to reuse the program section "Writeonce, run anywhere, reuse everywhere", that is, "write once, execute anywhere, it can be reused in all places, so it can provide a simple, compact and excellent problem solution for the JSP platform, which can greatly increase the upper limit of the system's functions and speed up the execution, and there is no need to sacrifice system performance. At the same time, the use of JavaBean technology can make the system easier to maintain, thus greatly improving the scope of JSP applications.

As described above Action to call JavaBean. Next we will review this mark after learning the Java Bean writing:

First, we mark the Bean by the id attribute in the tag so that the rest of the JSP page can correctly identify the Bean.

Secondly, use the scope attribute to determine the scope of use of the Bean. Scope attribute determines the scope of use.

Finally, the class attribute notifies the JSP page where to find the Bean, that is, find the. class file of the Bean. At the same time, we must specify the package name and class Name of the JavaBean, that is, class = package. class. Otherwise, the JSP Engine cannot find the corresponding Bean.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.