Introduction to Java Bean and its application

Source: Internet
Author: User
Tags event listener

Bean's Chinese meaning is "beans", as the name implies JavaBean is aJava applet。 JavaBean actually refers to a special Java class that is typically used toimplement some of the more 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.

I. Java Bean Technology Overview

Java beans are Java-based component models that are composed of properties , methods , and event 3 parts. 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 as an object that has some kind of functionality or that handles a business. As a result, the bean and its properties can also be accessed through Java code embedded within the JSP page.

The meaning of a bean is a reusable Java component. A component is a group of one or more classes that can be managed on its own, and the outside world does not know its internal information and how it operates. An object that uses it can only be manipulated by an interface.

two. Java Bean Authoring Specification

Java beans are actually Java classes written according to the naming and design specifications of the bean specified by the JavaBean technical standard. These classes follow an interface format, so that the function is named, the underlying behavior, and the behavior of inheritance or implementation, the greatest advantage of which is to implement the reusability of the code. The bean does not need to inherit a particular base class (BaseClass) or implement a specific interface (Interface). The Bean's writing specification enables the Bean's container (Container) to parse a Java class file and translate its methods (Methods) into attributes (properties), that is, to use the Java class as a Bean class. The Bean's writing specification includes the method of constructing the Bean class, defining properties, and writing rules for access methods.

2.1. The working mechanism of the bean component

The 5 important mechanisms of this component are defined in the JavaBeansVersion1.01 a specification:

(1) introspection (introspection): A build can publish its supported operations and properties, while also supporting the discovery of reusable object libraries in other components, such as user rights control and e-mail Auto-reply.

(2) Communication (communication): generates and collects message events for a component.

(3) continuous (persistence): The state of the storage component.

(4) properties: supports the control of component layout, including the space occupied by the component and the relative position of the component.

(5) Customization (customization): The developer can control the change mechanism required by the component.

2.2. Writing requirements for Java beans

Writing JavaBean must meet the following requirements:

(1) All JavaBean must be placed in a package.

(2) JavaBean must generate the public class class, and the file name should match the class name.

(3) All attributes must be encapsulated, one JavaBean class should not have public instance variables, and 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 with a matching public getter and setter method .

(5) The Java Bean class must have an empty constructor: The class must have a public constructor with no parameters, and the constructor should also set the default value of the property by invoking the setting method of each property .

2.3. Naming conventions for Java beans

The naming conventions for Java beans are as follows:

(1) package naming: all letters lowercase.

(2) class naming: Capitalize each word first letter.

(3) attribute name: The first word is all lowercase and the first letter of each word is capitalized.

(4) Method name: Same as property naming method.

(5) Constant name: capitalize all letters.

2.4. Java Bean Packages

Package-Package,javabean packages and the package meanings described in the previous chapters are basically the same, but there are differences, the packages described earlier are defined by Java itself, and JavaBean's packages are user-defined.

After each JavaBean source file is compiled into a. class file, it must be stored in the appropriate folder, and the folder that holds the. class file is a package. JavaBean packages must be stored in a specific directory, in each JSP engine to set the location of the JavaBean package , different JSP engine for the location of the JavaBean store has different provisions, such as in Tomcat, All packages of JavaBean are stored in the Web-inf/classes folder. If there is a multilevel directory, you need to include all the parent directories in the directory where the. class file is located in the package name, with the English punctuation between each level of the directory. Separated. For example, the following code: Packagejsp.example.mybean;

2.5. Structure of Java beans

(1) attribute: A member variable of the Java Bean class that describes the state of the JavaBean object, the change in the object's property value triggers the event, and the property itself is the source of the event.

(2) Method: In Java beans, functions and procedures are collectively referred to as methods, through methods to change and get the value of the property. Methods can be divided into construction methods, access methods and common methods.

(3) Event: The event is actually a special Java bean, the change of the property value triggers the event, the event fires the related object to react, the Java Bean registers the object event listener mechanism to receive, handle the event, it implements the communication between the Java bean.

Three. Java Bean Properties

In the previous section we briefly mentioned the properties of the JavaBean, the properties of Java beans and the properties of the objects in the generic Java program, or all object-oriented programming languages, are a concept, and the concrete embodiment in the program is the variables in the class. Attributes are divided into four categories, namely single-valued (simple), Index, Association (BOUND), and constraint (Constrained) properties. These properties are described in detail in this section.

3.1. Single-value (simple) attribute

The single-value (simple) attribute is the most common attribute type, which has a single data value that can be any data type in Java, including classes and interfaces.

Attributes are defined and the corresponding access methods are defined, with each single-valued attribute typically accompanied by a pair of get/set methods. The property name corresponds to the Get/set method name associated with the property . For example, if you have a property named "xxx," you will have the Setxxx and GetXXX methods.

In addition, the Boolean property is a special single-valued property that has only two allowed values: True and false, which can be accessed through the ISX method if there is a Boolean attribute named "xxx".

3.2. Index (Indexed) properties

If you need to define a batch of properties of the same type, it is cumbersome to use single-valued attributes, and to solve this problem, the index (Indexed) attribute is provided in JavaBean, which refers to the member variable of the array type in JavaBean. Use the Set/get method corresponding to this property to get the value of the array. Indexed properties set or get the value of an element in the property through the corresponding access method, or you can set or get the value of the entire property at once.

3.3. Association (BOUND) properties

The Association (Bound) property refers to notifying other objects when the value of the property changes. Each time the property value changes, this property triggers a PropertyChange event (in a Java program, the event is also an object). The event encapsulates the property name, the original value of the property, and the new value after the property has changed. This event is passed on to other beans, as to what action the beans should take to receive the event, defined by itself.

Property changes are called JavaBean events . External class objects related to Java bean events are called listeners (Listener). listeners may only be interested in JavaBean events related to a property, or they may be interested in events related to all attributes, so JavaBean provides two types of event listener registration and logoff methods , that is, global event Listener registration, logoff method and General Event listener registration, logoff method .

3.4. Constraint (Constrained) property

If the properties of a Java bean are changed, the related external class object first checks the rationality of the property change and then decides whether to accept the change , such that the JavaBean property is called the constraint (Constrained) attribute. When the change of the constraint property is denied, the method of changing the constraint property produces a constraint attribute change exception (propertyvetoexception), through this exception handling, the JavaBean constraint property reverts back to its original value, and a new property modification notification is sent for this restore operation.

The change to the constraint property may be rejected, so its setxxx differs from the setxxx of other JavaBean properties in general. The Write method for the constraint property is as follows:

Public void Setxxx (Xxxtype newxxx) throws Propertyvetoexception

Four. Java Bean method

4.1. Construction method

Java beans are constructed in the same way as the previous normal Java class, meaning that the properties and methods of the JavaBean are initialized , that is, to set an initial value for the defined property and method, and that the constructor name is the same as the JavaBean class name.

4.2. Access Methods

After you have defined the properties of the bean and initialized it by constructing a method, you must create an access method for other programs to access the Bean's properties. The access method is access to the properties defined in the component, including both read and write access methods. reading is a accessor , or getter, that is used to remove the value of the bean attribute, while writing is an assignment function that sets the Bean property , the setter. The following is a specific syntax format for the Bean property access method:

public void Setpropertyname (propertytypevalue);//Assign a value to a property, that is, write a method

Public PropertyType getpropertyname ();//Read property value, i.e. Read method

4.3. General methods

In addition to the access method for the property, you can also create a generic method in the bean to implement the call to the function, as long as the generic method in the bean is defined as a public method, it can be called by other programs.

Five. Java Bean Events

Event handling is one of the core of the JavaBeans architecture. Event-handling mechanisms allow components to be used as event sources to emit events that can be received by the described environment or other components . In this way, different components can be grouped together within the construction tools, and components communicate through the passing of events to form an application. Conceptually, an event is a passing mechanism in which a state changes between the source object and listener object. events have many different uses, such as mouse events, window boundary change events, keyboard events, and so on, that are often handled in Windows systems.

5.1. Event Model

Java Bean Event Model, the event source is a JavaBean class object that passes the time object of the property change to the event listener, who is responsible for handling the event. Event listeners must be registered with the event source.

5.2. Event Status Object

State information related to event occurrence is generally encapsulated in the event state object (Eventstate object) , which is a subclass of Java.util.EventObject. By design Custom, the name of this event state object class should end with an event. For example, the code is a mouse move event instance.

5.3. Event listener interface and event listener

Because the Java event model is based on method invocation, you need a way to define and organize the event manipulation methods. In JavaBeans, event manipulation methods are defined in the event Listener (EventListener) interface that inherits the Java.util.EventListener class , as specified, The name of the EventListener interface ends with listener. Any class that is to be manipulated in the EventListener interface must be defined in a way that implements this interface. This class is the event listener. For example, the following code:

A mouse Move event object is defined first

public class Mousemovedexampleeventextends Java.util.EventObject {

State information related to mouse movement events is included in this class

...

}

Listener interface that defines mouse movement events

Interface Mousemovedexamplelistener extends Java.util.EventListener {

The method that the listener of mouse movement event listeners should support is defined in this interface.

void mousemoved (mousemovedexampleevent Mme);

}

5.4. Event Listener Registration and logoff

In order for various possible event listeners to register themselves in the appropriate event source, the event stream between the source and event listener is established , and the event source must provide the method for registering and unregistering the event listener . In practice, the registration and logoff of event listeners uses the following standard design format:

public void add<listenertype> (< listenertype> listener);

public void remove<listenertype> (< listenertype> listener);

Here is a concrete example, first defining an event listener interface:

Import java.util.*;

public interface Modelchangedlistenerextends EventListener

{void modelchanged (EVENTOBJECTE);}

5.5. Adaptation class

The adaptation class is an extremely important part of the Java event model. in some applications, the transfer of events from source to listener is "forwarded" through the adaptation class. For example, when an event source issues an event, and there are several event listener objects that can receive the event, but only when the specified object reacts, an event adapter class is inserted between the event source and the event listener, and the adapter class specifies which listeners the event should respond to . The adaptive class becomes an event listener, and the event source actually registers the adapter class as listener in the listener queue, and the actual event responder is not in the listener queue, and the action that the event responder should do is determined by the adaptation class . At present, most of the development tools in the generation of code, event processing is through the adaptation class to do.

Six. Application of Java Bean in JSP

In the front we learned the Java bean writing, because JavaBean is for the reuse of the program paragraph has "writeonce, run anywhere, reuse everywhere", that is, "write once, anywhere execution, all places reusable" feature , so it can provide a simple, compact and excellent problem solution for JSP platform, which can greatly increase the function limit of the system, speed up the execution speed, and do not need to sacrifice the performance of the system. At the same time, using JavaBean technology can make the system easier to maintain, so it greatly improves the application scope of JSP.

The previous introduction of the JSP tag in the <jsp:useBean> action to invoke JavaBean, below we learn the Java bean after the writing, then to review this tag:

<jsp:usebean id= "Beanid" scope= "page|request|session|application" class= "Package.class"/>

First, we tag the bean with the id attribute in the tag so that the rest of the JSP page can correctly identify the bean.

Second, use the Scope property to determine the scope of the bean's use. Scope of use as determined by the scope property.

Finally, the Class property notifies the JSP page where to look for the bean, which is to find the Bean's. class file. Here we must specify both the package name and the class name of the JavaBean, which is class= "Package.class", or the JSP engine will not be able to find the corresponding bean.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to Java Bean and its application

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.