Home

MassLight presents

Chapter 2. JavaBeans

Goals After completing this chapter, the student will be able to
  • explain scope.
  • discuss implicit objects.
  • make a JavaBean. 
Prerequisites In order to complete this chapter successfully, the student must have
  • a basic understanding of the request-response cycle.
  • an understanding of JSP directives (<%@), scriptlets (<%), expressions (<%=), and declarations (<%!). 
  • a basic understanding of how to construct a JSP. 
Objectives The purpose of this chapter is to provide the student with the necessary information about implicit objects and JavaBeans.

What is Scope?

Scope is the idea that an object belongs to a certain part of an application. The five main scopes of a web application are request, response, page, session, and application. This means that an object may be a part of a request, a response, an individual page, a session, or an instance of the application. For example, if we said, "the employee object has session scope," we would mean that the employee object only existed within a certain session.


Every JSP has 5 implicit objects

This section discusses the implicit objects that represent the request, response, page, session, and application scopes. In JSPs, implicit objects are created by the JSP environment, so the developer does not need to initialize an implicit object. Implicit objects can only be used in JSP scriptlets and expressions.
 

Implicit object
Description
request  Represents the client’s request. An implementation of javax.servlet.http.HttpServletRequest
response Represents the JSP page’s response. An implementation of javax.servlet.http.HttpServletResponse
pageContext Represents the objects and attributes associated with a page. A subclass of javax.servlet.http.pageContext
session Represents the session associated with the request. An implementation of javax.servlet.http.HttpSession
application Represents the application associated with the request. An implementation of javax.servlet.ServletContext 

The request-response cycle

A very basic, generic request-response cycle consists of two parts. The request is where the client asks for data from the server, and response is where the server sends data to the client.


Capabilities of the request and response objects
In JSPs, the request-response cycle is represented mainly by the request and response objects. The request object handles the information sent from the client and the response object handles the information sent to the client.

Methods involved in the request

return type
method name
description
HttpSession getSession() returns the session associated with the request 
String getHeader(String headerName) returns the value associated with the header name of the request
Enumeration getHeaderNames() returns all the header names associated with a request
Cookie[] getCookies() returns the cookies associated with a request
Object getAttribute(String attributeName) returns the object that is paired with an attribute's name
void  setAttribute(String nameOfTheAttribute, Object valueOfTheAttribute) sets an attribute named nameOfTheAttribute to the value of valueOfTheAttribute

Methods involved in the response

return type
method name
description
void addCookie(Cookie cookie) adds the specified cookie to the response
void addHeader(String headerName, String value) adds the header to the response
void sendError(int statusCode) throws IOException sends a predefined error message back to the client
void sendRedirect(String newURL) throws IOException redirects the client browser to a different URL

A JSP using the request and response objects

(If you have not already done so, you can download this and other examples used in this course. Mac OS X or other UNIX users click here instead.)

code/Chapter2/RequestResponse/requestresponse.jsp
<%@ page language="java" %>
<HTML>
   <BODY>
     character encoding = <%= response.getCharacterEncoding() %> 
     <br/><br/>

     Headers 
     <br/><br/> 
     <%  java.util.Enumeration headerNames = request.getHeaderNames(); 
         while(headerNames.hasMoreElements()) { 
            String headerName = (String)headerNames.nextElement(); 
            String header = (String)request.getHeader(headerName); 
     %> 
            <%= headerName %> = <%=header%> 
            <br/> 
     <%  } %>
   </BODY>
</HTML>


Three parts of a web application

Information in a web application can be stored in the application scope, the session scope, and the page scope. The page scope refers to all information that only pertains to a specific instance of a given page. The server keeps the page-specific information as long as the page exists. The session scope contains information pertaining to a session instance. The application scope contains information that is available to all sessions in the application, as long as the application is running.


The pageContext, session and application objects

A programmer can access information stored in the page, the session, and the application scope, using the pageContext, session, and application objects, respectively.

Basic pageContext methods

return type
method name
description
Object findAttribute(String attributeName) searches the page, session, application and request scopes for an attribute named attributeName - it returns the attribute or null, if the attribute does not exist
Object getAttribute(String attributeName) returns the object that is paired with an attribute's name
void setAttribute(String nameOfTheAttribute, Object valueOfTheAttribute) sets an attribute named nameOfTheAttribute to the value of valueOfTheAttribute
HttpServletRequest getRequest() returns the request object associated with the page
HttpServletResponse getResponse() returns the response object associated with the page

Basic session methods

return type
method name
description
Object getAttribute(String attributeName) returns the object that is paired with an attribute named attributeName
void setAttribute(String nameOfTheAttribute, Object valueOfTheAttribute) sets an attribute named nameOfTheAttribute to the value of valueOfTheAttribute
String[] getAttributeNames() returns an array of the names of the attributes for a given session

Basic application methods

return type
method name
description
Object getAttribute(String attributeName) returns the object that is paired with an attribute's name
void setAttribute(String nameOfTheAttribute, Object valueOfTheAttribute) sets an attribute named nameOfTheAttribute to the value of valueOfTheAttribute
Enumeration getAttributeNames() returns an array of the names of the attributes for a given application

A JSP using the pageContext, session, and application implicit objects

Here is a JSP that uses the pageContext, session, and application implicit objects.

code/Chapter2/ImplicitObjects/implicitobjects.jsp
<%@ page language="java" %> 
<%   if (pageContext.getAttribute("pageCount")==null) { 
        pageContext.setAttribute("pageCount", new Integer(0)); 
     }
     if (session.getAttribute("sessionCount")==null) { 
        session.setAttribute("sessionCount",new Integer(0)); 
     } 
     if (application.getAttribute("appCount")==null) {
        application.setAttribute("appCount",new Integer(0)); 
     } 
%> 
<HTML> 
  <BODY> 
     <% Integer count = (Integer)pageContext.getAttribute("pageCount"); 
        pageContext.setAttribute("pageCount", new Integer(count.intValue()+1)); 
        Integer count2 = (Integer)session.getAttribute("sessionCount"); 
        session.setAttribute("sessionCount",new Integer(count2.intValue()+1)); 
        Integer count3 = (Integer)application.getAttribute("appCount"); 
        application.setAttribute("appCount",new Integer(count3.intValue()+1)); 
     %> 
     Page Count = <%= pageContext.getAttribute("pageCount")%> 
     <br/>Session count = <%= session.getAttribute("sessionCount")%> 
     <br/>Application count = <%= application.getAttribute("appCount")%> 
     <br/>Time = <%=  new java.sql.Time(System.currentTimeMillis()) %> 

   </BODY> 
</HTML>


Using Java Classes with JSP

Not all the code for a JSP needs to be written in the JSP itself. In fact, in good coding practice no code should be found in the JSP. This provides greater separation between the clients' view of the application and the logic of the application. Separation between logic and presentation means a more easily modifiable application.

jsp:useBean creates an instance of a specified class that is usable in a JSP. The instance of a Java class in a JSP is commonly referred to as a bean or a JavaBean. In order to create an instance, named greeter, of a custom class named Greetings with a package named thePackage, a JSP must state the following:
 

<jsp:useBean id="greeter" class="thePackage.Greetings" scope="session" />

The scope attribute specifies whether the instantiated object has a page, session, or application scope. The JSP can then make calls to the object's methods in scriptlets and/or declarations:
 

<% 
      greeter.setNameOfPersonToBeGreeted("Jill"); 
      greeter.setLanguage("Spanish");
%>
<%=   greeter.sayHello()  %>
<%=   greeter.sayGoodBye() %>

Naming Confusion: Two Types of JavaBeans

It is important to distinguish between a JavaBean used in a GUI development tool and a JavaBean used in a server-side application. This chapter discusses the later type of JavaBean. A JavaBean, or sometimes just called a bean, is basically an instance of a Java class. The two main characteristics of a server-side JavaBean are that accessor and mutator methods should be provided for all properties in the Java class and that the JavaBean may be persistent.

JavaBeans are normally deployed as part of a package. For this chapter, we will put our JavaBeans in the com.masslight.beans package.

When deploying a JavaBean as part of a web application, the package structure is recreated as a nested directory structure within the WEB-INF/classes/ directory. So our com.masslight.beans package will become the directory path WEB-INF/classes/com/masslight/beans/, and our Java classes will go inside that directory.


FirstBean: a simple JavaBean

Do this:

  1. Create the following directory structure. Create a FirstBean directory to hold all of the files for this web application, then within that, create a WEB-INF directory, then within that create a classes directory, then com, then masslight, then beans. Whew!
code/Chapter2/FirstBean
FirstBean
  |
  +-- beanExample.jsp (*)
  |
  +-- WEB-INF
        |
        +-- web.xml (*)
        |
        +-- classes
              |
              +-- com
                    |
                    +-- masslight
                          |
                          +-- beans
                                |
                                +-- GreeterBean.java (*)

(*) denotes a file

  1. Create the JSP in the FirstBean directory:
code/Chapter2/FirstBean/beanExample.jsp
<%@ page language="java" %>
<html>
   <head><title>Hello Example</title></head>
   <body>
     <jsp:useBean id="greeter" class="com.masslight.beans.GreeterBean" scope="session"/>
     <%= greeter.sayHello() %>
   </body>
</html>

  1. Create the web.xml file in the WEB-INF directory:
code/Chapter2/FirstBean/WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
</web-app>

  1. Create the Java file in the FirstBean/WEB-INF/classes/com/masslight/beans/ directory:
code/Chapter2/FirstBean/WEB-INF/classes/com/masslight/beans/GreeterBean.java
package com.masslight.beans;

public class GreeterBean {
    public String sayHello() {
        return("Hello, World!");
    }
}

  1. Change to the beans directory and compile the Java file with javac, Sun's command-line Java compiler:
c:\j2ee\code\Chapter2\FirstBean\WEB-INF\classes\com\masslight\beans> javac *.java
  1. Change back to the FirstBean directory and create the .war file, using the jar utility like you did in the previous chapter
c:\j2ee\code\Chapter2\FirstBean> jar cvf FirstBean.war *.jsp WEB-INF
  1. Deploy the web application by copying the .war file to the JBoss deployment directory
c:\j2ee\code\Chapter2\FirstBean> copy FirstBean.war c:\j2ee\jboss\deploy\
  1. Test the application by going to http://localhost:8080/FirstBean/beanExample.jsp

Accessor and mutator methods

JavaBeans require properties to have accessor and mutator methods. A property is another name for a class-wide variable. Accessors provide a standardized way of accessing the value of a property. Mutators provide a standard way to modify the value of a property. In fact, it is good coding practice to provide and use accessor and mutator methods for properties in all Java classes. To make the accessor and mutator methods for a property, the standard practice is to prepend the name of the property with the word 'get' for the get method name and 'set' for the set method name. In the accessor and mutator methods' names, the property name is capitalized, though the property's name should be declared in the lower case. An example of the accessor and mutator methods for a simple variable of type variable_type and name exampleVariable would be:
 

public void setExampleVariable(variable_type value)
public variable_type getExampleVariable()

If the variable_type is boolean, the set method would be the same and the get method would be:
 

public boolean isExampleVariable()

If the property is an array, then the getter and setter methods are:
 

public variable_type[] getExampleVariable()
public variable_type getExampleVariable(int location_in_array) 
public void setExampleVariable(variable_type[])
public void setExampleVariable(int location_in_array, variable_type value)

SecondBean: a JavaBean with accessor and mutator methods

Do this:

  1. Create the directory structure. Create a SecondBean directory to hold all the files for this web application. Within SecondBean, the directory structure is the same as it was for FirstBean.
code/Chapter2/SecondBean
SecondBean
  |
  +-- beanExample.jsp (*)
  |
  +-- WEB-INF
        |
        +-- web.xml (*)
        |
        +-- classes
              |
              +-- com
                    |
                    +-- masslight
                          |
                          +-- beans
                                |
                                +-- NumberBean.java (*)

(*) denotes a file

  1. Create the JSP in the SecondBean directory:
code/Chapter2/SecondBean/beanExample.jsp
<%@ page language="java" %>
<jsp:useBean id="number" class="com.masslight.beans.NumberBean" scope="session"/>
<html> 
<head><title>Second Bean Example</title></head>
<body> 
  JavaBean state starts at <%= number.getIntegerProperty() %>
  <% number.setIntegerProperty(2); %> 
  <br> JavaBean state is now <%= number.getIntegerProperty() %>
  </body> 
</html>

  1. Create the web.xml file in WEB-INF
code/Chapter2/SecondBean/WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
</web-app>

  1. Create the Java file in WEB-INF/classes/com/masslight/beans/
code/Chapter2/SecondBean/WEB-INF/classes/com/masslight/beans/NumberBean.java
package com.masslight.beans;

public class NumberBean {
    private int integerProperty = 1;

    public int getIntegerProperty() {
        return integerProperty;
    }
    public void setIntegerProperty(int newInteger) {
        integerProperty = newInteger;
    }
}

  1. Compile the Java classes, in the same way you did with FirstBean
  2. Create the .war file, in the same way you did with FirstBean. Call it SecondBean.war
  3. Deploy the web application by copying SecondBean.war to the JBoss deployment directory
  4. Test the application at http://localhost:8080/SecondBean/beanExample.jsp

What is Persistence?

The properties of a bean can be saved and then retrieved at a later time - in other words, a bean can be persistent. In order to be persistent, a JavaBean needs to implement the java.io.Serializable interface. The java.io.Serializable interface does not have any methods to implement. It is used to indicate that the class that implements it can be saved and retrieved. To learn how to save and retrieve a bean, please look at the following example.


SerializableBean: a JavaBean with Persistence

Do this:

  1. Create the directory structure. Create a SerializableBean directory; within that, the structure is the same as FirstBean and SecondBean.
code/Chapter2/SerializableBean
SerializableBean
  |
  +-- firstPage.jsp (*)
  |
  +-- secondPage.jsp (*)
  |
  +-- WEB-INF
        |
        +-- web.xml (*)
        |
        +-- classes
              |
              +-- com
                    |
                    +-- masslight
                          |
                          +-- beans
                                |
                                +-- SerializableBean.java (*)

(*) denotes a file

  1. Create 2 JSPs in the SerialiableBean directory:
code/Chapter2/SerializableBean/firstPage.jsp
<%@ page language="java" %> 
<jsp:useBean id="theBean" class="com.masslight.beans.SerializableBean" scope="page" /> 

<html> 
     <title>Serialized bean, Page One</title> 
     <body> 

      <br>
         <%= theBean.getIntegerProperty() %>
         <% theBean.setIntegerProperty(8+theBean.getIntegerProperty()); %> 
      <br>
         <%= theBean.getIntegerProperty() %>
         <%
           theBean.save(theBean, "theBeanFile.ser");
         %>
      <br>
      <a href="http://localhost:8080/SerializableBean/secondPage.jsp">click here</a>

     </body> 
</html>

code/Chapter2/SerializableBean/secondPage.jsp
<%@ page language="java" %> 
<jsp:useBean id="saver" class="com.masslight.beans.SerializableBean" scope="session"/>

<html> 
   <title>Serialized bean, Page Two</title> 
   <body> 
     <%
         com.masslight.beans.SerializableBean anotherBean = 
 (com.masslight.beans.SerializableBean)saver.retrieve("theBeanFile.ser");
     %> 
     <%= anotherBean.getIntegerProperty() %>

     <br>
     <%  anotherBean.setIntegerProperty(8+ anotherBean.getIntegerProperty()); %>
     <%= anotherBean.getIntegerProperty() %>

   </body> 
</html>

  1. Create the web.xml file in WEB-INF
code/Chapter2/SerializableBean/WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
</web-app>

  1. Create the Java file in WEB-INF/classes/com/masslight/beans/
code/Chapter2/SerializableBean/WEB-INF/classes/com/masslight/beans/SerializableBean.java
package com.masslight.beans;
import java.beans.*;
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class SerializableBean implements Serializable {
    private int integerProperty=8;

    public int getIntegerProperty() {
        return integerProperty;
    }
    public void setIntegerProperty(int newInteger) {
        integerProperty= newInteger;
    }

    public boolean save(Object object, String file_name) {
        boolean status = true;

        try{
            FileOutputStream fos;
            ObjectOutputStream oos;
            fos = new FileOutputStream(file_name);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.close();
        }
        catch (Exception e) {
            status = false;
            System.out.println("Error with saving: " + e.toString());
        }
        return status;
    }
    public Object retrieve(String file_name) {
        Object object = new Object();

        try {
            FileInputStream fis;
            ObjectInputStream ois;
            fis = new FileInputStream(file_name);
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
            ois.close();
        }
        catch (Exception e) {
            System.out.println("Error with retrieval: " + e.toString());
        }
        return object;
    }
}

  1. Compile the Java file.
  2. Create SerializableBean.war
  3. Deploy
  4. Test at http://localhost:8080/SerializableBean/firstPage.jsp

Exercises

Exercise 1. Application vs. session

Make a JSP that displays the last time it was ever hit by anyone, and the last time it has been hit by you personally. If it has never been hit by anyone before, it should display "This application has never been used before." If this is your first time, it should display "This is your first time using this application." (Hint: use the application and session objects.

Exercise 2. Calculator

Make a JavaBean that does simple arithmetic. The application should consist of a JSP page and a JavaBean. The JavaBean should provide methods, that given two numbers, produce the sum, the difference, the product, and the quotient. The JavaBean should then produce output for the JSP similar to the following screen shot. The calls to the JavaBean methods from the JSP should look like this:


<%= calculator.add(1, 1) %><br>
<%= calculator.subtract(4, 2) %><br>
<%= calculator.multiply(4, 5) %><br>
<%= calculator.divide(30, 6) %>