Online-Academy

Look, Read, Understand, Apply

Menu

JavaBeans

Java Beans Example

package beans;
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;
   }
}

JSP file to access StudentsBean

<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page import="beans.StudentsBean"%>
<html>
   <head>
      <title>get and set properties Example</title>
   </head>
   
   <body>
   <jsp:useBean id = "date" class = "java.util.Date" /> 
      <p>The date/time is <%= date %>
	  
<jsp:useBean id = "students" scope="page" class = "beans.StudentsBean"> 
         <jsp:setProperty name = "students" property = "firstName" value = "Dinesh"/>
         <jsp:setProperty name = "students" property = "lastName" value = "Bajracharya"/>
         <jsp:setProperty name = "students" property = "age" value = "10"/>
      </jsp:useBean>

      <p>Student First Name: 
         <jsp:getProperty name = "students" property = "firstName"/>
      </p>
      
      <p>Student Last Name: 
         <jsp:getProperty name = "students" property = "lastName"/>
      </p>
      
      <p>Student Age: 
         <jsp:getProperty name = "students" property = "age"/>
      </p>   
   </body>
</html>