JavaBean basics, javabean
URL: http://www.cnblogs.com/archimedes/p/javabean.html.
About JavaBean
JavaBean is a software component model described in the Java language. In short, it is a Java class that can be reused. JavaBean can be divided into visual components and non-visual components. The visual components include simple GUI elements (such as text boxes and buttons) and some report components. Non-visual components are frequently used in actual development and play a vital role in applications. Its main functions are to encapsulate business logic (function implementation) and database operations (such as data processing and database connection.
Why useJavaBean
In the actual development process, repeated code or paragraphs usually occur, which greatly reduces the reusability of the program and wastes time. Using JavaBean can greatly simplify the program design process and facilitate reuse of other programs.
The Application of JavaBean on the server side has a very powerful advantage. The non-visual JavaBean can well achieve the separation of control logic, business logic, and presentation layer, thus greatly reducing the coupling between them. Non-visualized JavaBean is mostly used for background processing, which makes the system flexible.
JavaBean is a type of Java program. It uses the same syntax as other similar Java programs. Using JavaBean in a program has the following advantages:
(1) code reuse.
(2) easy to write, easy to maintain, and easy to use.
(3) It can be compressed into jar files and applied in the network with a smaller volume
(4) It is completely written in Java and can be used on any platform installed with the Java Runtime Environment without re-compiling.
JavaBeanForm and elements
Compiling JavaBean is to compile a Java class. An object created by this class is called a Bean. To let the application building tool (such as the JSP Engine) that uses the bean know the attributes and methods of the bean, follow the following rules on the method naming of the class:
(1) if the name of the member variable of the class is xxx, two methods can be used in the class to change or obtain the value of the member variable, that is, to change or obtain the attribute:
● GetXXX (): used to obtain the property xxx.
● SetXXX (): used to modify the property xxx ..
(2) For a boolean member variable, that is, a boolean logical attribute, "is" can be used to replace the preceding "get" and "set ".
(3) The access attributes of methods in the class must be public.
(4) If there is a constructor in the class, the constructor is public and has no parameters.
JavaBean example:
import java.io.Serializable;public class JavaBeanDemo implements Serializable{ private int id; private String name; JavaBeanDemo(){} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}JavaBean attributes
In the design of JavaBean, this Bean can be divided into four categories based on different functions of its attributes, namely Simple attribute setting and Indexed), Bound, and Constrained ).
1. Simple attributes
The Simple attribute of JavaBean is a variable of the general data type, and the getXXX () and setXXX () methods are named by attributes. For example:
Public class Hello {Hello () {}// No parameter constructor private String name; // defines the simple attribute name private boolean info of the Stringl type; public String getName () {// getXXX () method of the simple attribute return name;} public void setName (String name) {// setXXX () method of the simple attribute this. name = name;} public boolean isInfo () {// return info;} public void setInfo (boolean info) {// Boolean setXXX method this.info = info ;}}
The index attribute (Indexed attribute) of JavaBean indicates an array value or a set. Like the Simple attribute, you can use the getXXX () and setXXX () methods to obtain the value. For example:
Public int [] array = new int [8]; public int [] getArray () {// return the entire array return array;} public void setArray (int [] array) {// assign this to the entire array. array = array;} public void setArray (int index, int value) {// assign this to an element in the array. array [index] = value;} public int getArray (int index) {// return a value in the array return array [index];}
In addition to arrays, you can also use the Indexed attribute to represent collection classes.
3. constraint attributes
Bound is also called an association attribute. It notifies other objects 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. This type of event is passed to other beans. The Bean that receives the event should be defined by itself. Beans that contain Association attributes must have the following functions:
(1) allow event listeners to register and deregister Attribute Modification events related to the event;
(2) When modifying an association attribute, You can trigger the attribute modification event on the listener.
The java. beans. PropertyChangeSupport class is used to create an object of the PropertyChangeSupport class, which can be used to manage the list of registered listeners and send notifications of Attribute Modification events. JavaBean also needs to implement the addPropertyChangeLinster () method and removePropertyChangeLinster () method to add and cancel listener for attribute changes.
3. Restrict attributes
Constrained indicates that when the value of this attribute changes, other external Java objects that have established a connection with this attribute can reject the change of this attribute value (the listener who restricts the attribute can throw PropertyVetoException to prevent the change of this attribute value ), the Bean itself can also reject changes to the Bean property value.
A restricted attribute has two types of listeners: listener with attribute changes and listener who cancel attribute changes. The listener who cancels attribute changes has corresponding control statements in its own object code. When the monitored restricted attribute changes, the listener determines whether to reject the change of this attribute value in the control statement.
Use the fireVetoableChange () method of the java. beans. VetoableChangeSupport class to pass the attribute name, change the previous value, and change the value. JavaBean also needs to implement the addVetoableChangeLinster () method and the removeVetoableChangeLinster () method to add and remove listeners for attribute changes.
Note: Due to the restriction attribute, you must pay special attention to Exception Handling Methods During programming.
Scope of JavaBean
1. pageScope
The page scope has the smallest range among the four types. Each time the client requests access, a JavaBean object is created. The valid range of the JavaBean object is the current page file requested by the customer to access. After the customer executes the current page file, the JavaBean object ends its life.
Within the page range, a new JavaBean object is generated every time you access the page file. The life cycle of the original JavaBean object has ended.
2. requestScope
When scope is request, after the JavaBean object is created, it will exist throughout the lifecycle of the request. The request object is a built-in object, the getParameter method can be used to obtain the data information in the form.
The JavaBean in the Request range has a great relationship with the request object. In addition to the page, it also includes the use of Action elements <jsp: include> and <jsp: forward> All JSP programs connected by these two operation commands can share the same JavaBean object.
3. session Scope
When the scope is a session, after the JavaBean object is created, it will exist throughout the lifecycle of the session. The session object is a built-in object. When a user accesses a webpage through a browser, A session object representing the link is created, and files in the same session share the javajan object. At the end of the session life cycle, the life of the JavaBean object is also over. In the same browser, the JavaBean object exists in a session. When you re-open the new browser, a new session is started. Each session has its own JavaBean object.
4. application Scope
When the scope is application, after the JavaBean object is created, it will exist throughout the life cycle of the host or virtual host, and the application scope is the longest life cycle of the JavaBean. All files on the same host or virtual host share this JavaBean object. If the server is not restarted, the JavaBean object of the scope application will be stored in the memory and processed at any time until the server is closed, the resources it occupies in the memory will be released. During this period, the server does not create a new JavaBean Component, but creates a synchronous copy of the source object. Any changes to the copy object will change the source object, however, this change will not affect other existing copy objects.
Obtain scope data by using JavaBean
The following example describes four scopes:
First, create a JavaBean: "Scope. java"
Package scope; public class Scope {public Scope () {}// No parameter constructor private int number = 0; // The value of the initialization variable number is 0 public int getNmuber () {// Add and return the variable number value number ++; return number;} public void setNumber (int newNumber) {this. number = newNumber; // assign a new value to the variable number }}
Then, create a page file named "scope. jsp" to display the specific differences between the scope of the JavaBean. Main Code:
<Body> <jsp: useBean id = "pagination" scope = "page" class = "scope. scope "/> <% out. println ("the data obtained using page is:" + pagination. getNmuber (); %> <jsp: useBean id = "requestScope" scope = "request" class = "scope. scope "/> <% out. println ("the data obtained using the request is:" + requestScope. getNmuber (); %> <jsp: useBean id = "sessionScope" scope = "session" class = "scope. scope "/> <% out. println ("data obtained using session:" + sessionScope. getNmuber (); %> <jsp: useBean id = "applicationScope" scope = "application" class = "scope. scope "/> <% out. println ("data obtained using application:" + applicationScope. getNmuber (); %> </body>
Use JavaBean to calculate the circle perimeter and area
(1) create a JavaBean named "Circle. java". This type of file mainly implements round mathematical computation. The Code is as follows:
Package circle; public class Circle {private int radius = 1; // defines the private variable radius to indicate the Circle radius public circle () {}// No parameter constructors public int getRadius () {return radius; // return variable radius} public void setRadius (int rRadius) {radius = rRadius; // assign a value to the variable radius} public double circleLength () {return Math. PI * radius * 2.0; // calculate the circumference of the circle} public double circleArea () {return Math. PI * radius; // calculate the area of the circle }}
(2) create a page file named "radiusInput. jsp". The page file prompts you to enter the circle radius. The main code is as follows:
<Body> <form id = "form1" name = "form1" method = "post" action = "circle. jsp "> enter the circle radius: <input name = "radius" type = "text" id = "radius"/> <input type = "submit" name = "submit" value = "Start Calculation"/> </form> </body>
(3) create a page file named "circle. jsp". The page file calculates the area and perimeter of the circle. The main code is as follows:
<Body> <jsp: useBean id = "circleBean" scope = "session" class = "circle. circle "/> </p> <% int radius = Integer. parseInt (request. getParameter ("radius"); circleBean. setRadius (radius); out. println ("the circle radius is:" + circleBean. getRadius (); out. println ("the circumference of the circle is:" + circleBean. circleLength (); out. println ("the area of the circle is:" + circleBean. circleArea (); %> </body>
(4) run the program: