WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JSP JavaBean


JavaBean is a special Java class written inthe Java language and adheres tothe JavaBean API specification.

What follows arethe unique characteristics of JavaBeans compared to other Java classes:

  • Provide a defaultparameterless constructor.
  • Need to be serialized and implementthe Serializable interface.
  • There may be a series of read-writeproperties.
  • There may be a series of getters or setters .

JavaBean attributes

Theproperties of a JavaBean object should be accessible.thisproperty can be any legal Java data type, including custom Java classes.

Theproperties of a JavaBean object can be read-write, read-only, or write-only.theproperties of a JavaBean object are accessedthrough two methodsprovided inthe JavaBean implementation class:

Method Description
get propertyName () For example, ifthe name oftheproperty is myName,thenthe name ofthe method is written as getMyName () to readtheproperty.this method is also called an accessor.
set propertyName () For example, ifthe name oftheproperty is myName,thenthe name ofthe method is written as setMyName () to writetheproperty.this method is also called a writer.

A read-onlypropertyprovides onlythe getPropertyName () method, and a write-onlypropertyprovides onlythe setPropertyName () method.


JavaBeanprogram example

This isthe StudentBean.java file:

package com.runoob;

public class StudentsBean implements java.io.Serializable
{
   private String firstName = null;
   private String lastName = null;
   private int age = 0;

   public StudentsBean() {
   }
   public String getFirstName(){
      return firstName;
   }
   public String getLastName(){
      return lastName;
   }
   public int getAge(){
      return age;
   }

   public void setFirstName(String firstName){
      this.firstName = firstName;
   }
   public void setLastName(String lastName){
      this.lastName = lastName;
   }
   public void setAge(int age) {
      this.age = age;
   }
}

Compile StudentBean.java file(The last instance will be used):

$ javac StudentsBean.java

Obtained after Compile StudentBean.class file,Copy it to <JSPproject>/WebContent/WEB-INF/classes/com/runoob,As shown below: