Sunday, November 17, 2013

Java Beans

Here are some of my notes on learning about Java Beans :

  • Java Beans are reusable software components for Java. 
  • They are classes that encapsulates many objects into a single object (the bean).
  • They are serializable (to save the state of an object), have a no-argument constructor (to instantiate the object), and allow access to properties using getter and setter methods.
As an example, here is the User beans with 2 properties :

package beans;  
public class User {  
      private String email;  
      private String password;  
      public String getEmail() {  
           return email;  
      }  
      public void setEmail(String email) {  
           this.email = email;  
      }  
      public String getPassword() {  
           return password;  
      }  
      public void setPassword(String password) {  
           this.password = password;  
      }  
}  

After create that class, we can call it from JSP file either to set the value or get the value.

  1. setbean.jsp
    
     <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
       pageEncoding="ISO-8859-1"%>  
     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">  
     <html>  
     <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
     <title>Set beans</title>  
     </head>  
     <body>  
     
     <jsp:useBean id="user" class="beans.User" scope="session"></jsp:useBean>  
     <jsp:setProperty property="email" name="user" 
         value="fahmi@gmail.com" />  
     <jsp:setProperty property="password" name="user" value="letmein" />  
     
     </body>  
     </html>  
    
    

  2. getbean.jsp
    
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
       pageEncoding="ISO-8859-1"%>  
     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">  
     <html>  
     <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
     <title>Insert title here</title>  
     </head>  
     <body>  
     <jsp:useBean id="user" class="beans.User" scope="session"></jsp:useBean>  
     Email : <%= user.getEmail() %>  
     </body>  
     </html>  
    
Once those files created, start Apache Tomcat Server, access setbean.jsp to set the value for User beans, then on the same browser access getbean.jsp to see the User beans value.

No comments: