Trainers' thoughts on Java and related technologies

A JavaBean is a specialized Java class. In this short JavaBeans tutorial, I’ll show you the rules with which a JavaBean must comply and then I’ll give you examples of creating a JavaBean, first in straight Java and then in JSP.

JavaBean Rules

  • A JavaBean must have a public, no-argument constructor (a default constructor). This is required so that Java frameworks can facilitate automated instantiation.
  • The JavaBean class attributes must be accessed via accessor and mutator methods that follow a standard naming convention (getXxxx and setXxxx, isXxxx for boolean attributes). It’s important to note that an “attribute” is a named memory location that contains a value, while a “property” refers to this set of methods used to access an attribute. This allows frameworks to automate operations on attribute values.
  • The JavaBean class should be serializable. This allows Java applications and frameworks to save, store, and restore the JavaBean’s state.

JavaBean Example

Here is a simple JavaBean example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// The class is serialized for IO operations
public class Person implements java.io.Serializable {
	// attributes declared as private
	private String name;
	private boolean deceased;
 
 
	// Default Constructor
	public Person() { }
 
	// getXxxx to access the name attribute
	public String getName() {
		return this.name;
	}
 
	// setXxxx to mutate the name attribute
	public void setName(String name) {
		this.name = name;
	}
 
	// isXxxx to access boolean attribute
	public boolean isDeceased() {
		return this.deceased;
	}
 
	// setXxxx to mutate boolean attribute
	public void setDeceased(boolean deceased) {
		this.deceased = deceased;
	}
}

JavaBean Example with JSP

This JavaBean can be implemented by a JavaServer Page (JSP) without all the code used to instantiate it and initialize its attributes:

1
2
3
4
<!-- Creates an instance of the Person JavaBean -->
<jsp:useBean id="person" class="Person" scope="page"/>
<!-- Sets the properties of the bean with the values of the HTML form -->
<jsp:setProperty name="person" property="*"/>

In my next article, I’ll delve into this JSP/JavaBean relationship a bit more.

JavaBeans are covered in different forms through Webucator’s Java classes.

No TweetBacks yet. (Be the first to Tweet this post)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Webucator, Inc. All rights reserved. | Toll Free: 877-932-8228 | UK: 0808-101-3484 | From outside the USA: 315-849-2724 | Fax: 315-849-2723