Before we look into more advanced features of JSP, let’s talk about JavaBeans.
A JavaBean, sometimes just called bean, it’s a class that follows two simple rules.
- Include a public zero-argument constructor, also known as default constructor.
- Provide get, set, and is methods for properties. The is method is used instead of get for boolean properties.
That’s all.
Really the only required rule is to have a zero-argument constructor, but a class with no properties is not very useful, is it?
Some people say that a JavaBean must also implement the Serializable interface. This is not really necessary, but it’s not a bad idea, plus it’s pretty easy to do.
Let’s take a look at the Product class from our previous sample.
package ServletSample.Business; public class Product { private int id; private String name; private float price; 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; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Product(){ this.id = -1; this.name = ""; this.price = 0f; } public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } }
This class is a JavaBean because the first constructor doesn’t take any arguments. Also, I define get and set methods for the properties. In this example, my properties are Id, Name, and Price.
Note about constructors: If you don’t define any constructor in your class, a default constructor is assumed by the compiler. So I could define my class like this, and it would still be considered a JavaBean.
package ServletSample.Business; public class Product implements java.io.Serializable { private int id; private String name; private float price; 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; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }
Note there’s no constructor this time.
Also note how the JavaBean is now serializable. The Serializable interface doesn’t require us to implement any method.
In the next post, we’ll do some interesting things with JavaBeans.
Please leave a comment if you have any question.