JavaBean is a Java class that is mainly responsible for holding on to some data without a large degree of functionality built into the class.
Typically, a JavaBean is a Java class that:
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.
Typically, a JavaBean is a Java class that:
- Implements the Serializable interface
- Exposes its properties via getter/setter methods
- Has a no-argument constructor
- Implementing the Serializable interface is required if you have a need to save the object (with its data) somewhere (file system, database, refrigerator, etc).
- It's standard practice is to allow the manipulation of the properties within the class via getter/setter methods.
- Sometimes we may add further methods to a JavaBean class besides the standard getter/setter methods if the nature of particular functionality makes sense to be encapsulated within the bean class, but we make an effort to make such changes the exception to the rule, since this can dirty up your bean classes, which can spread out functionality within your application which can make code maintainability more difficult.
Simple example of java bean class
- //Employee.java
- package mypack;
- public class Employee implements java.io.Serializable
- {
- private int id;
- private String name;
- public Employee()
- {
- }
- public void setId(int id)
- {
- this.id=id;
- }
- public int getId()
- {
- return id;
- }
- public void setName(String name)
- {
- this.name=name;
- }
- public String getName()
- {
- return name;
- }
- }
How to access the java bean class?
To access the java bean class, we should use getter and setter methods. |
<jsp:useBean id="id" class="bean's class" scope="bean's scope"> <jsp:setProperty name="bean's id" property="property name" value="value"/> <jsp:getProperty name="bean's id" property="property name"/> ........... </jsp:useBean>
JavaBeans Properties:
A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean's implementation class:
Method | Description |
---|---|
getPropertyName() | For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor. |
setPropertyName() | For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator. |
No comments:
Post a Comment