Simplifying JSP Pages with JavaBeans

One of the problems with writing JSP pages is switching between the Java code and the HTML elements. It is easy to get confused and place syntax errors in the page that can be difficult and time consuming to identify. Using EL, JSTL and JavaBeans on a JSP page can reduce the amount of embedded Java code that has to be written (or indeed remove the need for embedded Java code entirely). JavaBeans and the built-in support in EL for accessing JavaBean properties also help to separate out the presentation and logic components of your application, allowing HTML developers to lay out the Web pages and the Java programmers to develop supporting JavaBeans.

What Is a JavaBean?

A bean is a self-contained, reusable software component. Beans are Java classes that are written to conform to a particular design convention (sometimes called an idiom). The rules for writing a JavaBean are as follows:

  • A bean must have a no argument constructor (that is a constructor with no parameters). As long as you do not declare any constructors, the compiler generates a no argument constructor for you as follows:

    public class NameBean {
      public NameBean () {}
    }
    
  • Beans can provide properties that allow customization of the bean. For each property, the bean must define getter and setter methods that retrieve or modify the bean property. For example, if a bean has a property called name, the bean class can define the methods getName() and setName().

  • The getter method must have no parameters and return an object of the type of the property. The setter method must take a single parameter of the type of the property and return a void. The following example shows a simple bean with a String property called name that can be queried and modified using the defined getter and setter methods.

    public class NameBean {
      private String name;
      public void setName (String name) {
        this.name = name;
      }
      public String getName () {
        return name;
      }
    }
    

NOTE

If a bean property has only a getter method, it is read-only; a write-only method only has a setter method. A property is read/write if it has both getter and setter methods.


Beans can also define business methods to provide additional functionality above and beyond manipulating properties.

Defining a JavaBean

JavaBeans are defined on the JSP using the tag <jsp:useBean>. This tag creates an instance of a JavaBean and associates it with a name for use on the JSP.

<jsp:useBean id="<bean name>" class="<bean class>" scope="<scope>">

The bean name and class are defined by the id and class attributes for the useBean tag.

The useBean tag also requires a scope attribute that defines the scope of the bean reference. The possible scope values are as follows:

  • page Only available on this page.

  • request Available for this HTTP request (this page and any pages the request includes or is forwarded to).

  • session The duration of the client session (the bean can be used to pass information from one request to another).

  • application The bean is added to the Web context and can be used by any other component in the Web application.

The following code creates an instance of a bean of class NameBean for the current request and associates it with the name myBean.

<jsp:useBean id="myBean" class="NameBean" scope="request"/>

This bean has been defined using an empty JSP element because the bean is ready to use as soon as it has been defined. However, if the bean must be initialized, an alternate syntax is shown next and described fully in the “Initializing Beans” section later in the chapter.

<jsp:useBean id="myBean" class="NameBean" scope="request" >
  <jsp:setProperty name="myBean" property="name" value="winston"/>
</jsp:useBean>

Setting Bean Properties

Bean properties are set using the setProperty element. This element requires a bean name (from the ID in the useBean element), a property, and a value attribute, as shown in the following:

<jsp:setProperty name="<bean name>"
  property="<property name>" value="<expression>"/>

To set the name of the example NameBean to winston, you would use the following:

<jsp:setProperty name="myBean" property="name" value="winston"/>

As with getProperty, the bean method can be called explicitly from a Java scriptlet:

<% myBean.setName("winston"); %>

A useful feature of the setProperty tag is that bean properties can also be initialized from the HTTP request parameters. This is accomplished by using a param attribute rather than the value attribute:

<jsp:setProperty name="<bean name>" property="<property name>" param="<name>"/>

The value of the named parameter is used to set the appropriate bean property. To use a request parameter called name to set the NameBean property of the same name, you could use the following:

<jsp:setProperty name="myBean" property="name" param="name"/>

In fact, the param attribute can be omitted if the property name is the same as the request parameter name. So the previous example could have been put more succinctly as follows:

<jsp:setProperty name="myBean" property="name"/>

A last form of the setProperty bean is employed when multiple parameters are used to initialize several bean properties. If the property name is set to *, all of the form request parameters are used to initialize bean properties with the same name:

<jsp:setProperty name="myBean" property="*"/>

CAUTION

The bean must define a property for every parameter in the HTTP request; otherwise, an error occurs.


Initializing Beans

Some beans require properties to be defined to initialize the bean. There is no mechanism for passing in initial values for properties in the jsp:useBean element, so a syntactic convention is used instead.

Conventionally, if a bean must have properties defined before it can be used on the Web page, the jsp:useBean is defined with an element body and the jsp:setProperty tags are defined in the useBean body to initialize the required properties.

For example, assuming that the simple NameBean example requires the name to be initialized, the following useBean syntax would be used:

<jsp:useBean id="myBean" class="NameBean" scope="request" >
  <jsp:setProperty name="myBean" property="name" value="winston"/>
</jsp:useBean>

Getting Bean Properties

Bean properties are retrieved using an EL variable or the <jsp:getProperty> element. With EL you can use the following to retrieve a property called name from the NameBean bean:

${myBean.name}

Before the introduction of EL the <jsp:getProperty> element was used to access a bean property. This element requires a bean name (from the ID defined in the useBean tag) and property attribute, as shown in the following:

<jsp:getProperty name="<bean name>" property="<property name>" />

The value of the property is converted to a string and substituted on the Web page.

The following example shows how to retrieve the name property from the NameBean defined earlier and use it as a level 2 heading:

<H2><jsp:getProperty name="myBean" property="name"/></H2>

An alternative method for accessing a bean property is to use the bean name and get property method inside a JSP scripting element (such as an expression). The following code is an equivalent JSP rendering of the previous examples:

<H2><%= myBean.getName() %></H2>

NOTE

Both the use of <jsp:getProperty> and scripting elements to access bean properties are likely to fall into disuse with the introduction of EL.


Using a Bean with the Agency Case Study

The next example uses the Agency case study code and refactors the name.jsp Web page shown in Listing 13.8 to use a JavaBean. This time, you will use a bean to hide the complex JNDI lookup and type casting needed to access the agency Session EJB.

The new JSP page is shown in Listing 13.9.

Listing 13.9. Full Text of agencyName.jsp
<HTML>
  <HEAD><TITLE>Agency Name</TITLE></HEAD>
  <BODY>
    <jsp:useBean id="agency" class="web.AgencyBean" scope="request" />
    <H1>${agency.agencyName}</H1>
  </BODY>
</HTML>

This is much simpler for a non-Java developer to work with. All of the code required to create the EJB using its JNDI name has been spirited away into a JavaBean of class web.AgencyBean. This bean has properties representing AgencyName, Applicants, Customers, Locations, and Skills and defines a large number of business methods whose only purpose is to delegate behavior to the underlying agency Session bean.

The full bean code is shown in Listing 13.10.

Listing 13.10. Full Text of web.AgencyBean.java
package web;

import java.rmi.*;
import java.util.* ;
import javax.ejb.* ;
import javax.naming.* ;

import agency.*;

public class AgencyBean
{
    Agency agency;

    public AgencyBean ()  throws NamingException, RemoteException,
                                 CreateException {
        InitialContext ic = null;
        ic = new InitialContext();
        AgencyHome agencyHome = (AgencyHome)ic.lookup("java:comp/env/ejb/Agency");
        agency = agencyHome.create();
    }

    public String getAgencyName() throws RemoteException {
        return agency.getAgencyName();
    }

    public Collection getApplicants() throws RemoteException {
        return agency.getApplicants();
    }

    public void createApplicant(String login, String name, String email)
                throws RemoteException, DuplicateException,
                        CreateException{
        agency.createApplicant(login,name,email);
    }


    public void deleteApplicant (String login)
                throws RemoteException, NotFoundException{
        agency.deleteApplicant(login);
    }
    public Collection getCustomers() throws RemoteException {
        return agency.getCustomers();
    }


   public void createCustomer(String login, String name, String email)
               throws RemoteException, DuplicateException,
                        CreateException{
        agency.createCustomer(login,name,email);
    }

    public void deleteCustomer (String login)
                throws RemoteException, NotFoundException {
        agency.deleteCustomer(login);
    }

    public Collection getLocations() throws RemoteException {
        return agency.getLocations();
    }

    public String getLocationDescription(String name)
                  throws RemoteException, NotFoundException {
        return agency.getLocationDescription(name);
    }

    public void updateLocation(String name, String description)
                throws RemoteException, NotFoundException {
        agency.updateLocation(name,description);
    }

    public void addLocation(String name, String description)
                throws RemoteException, DuplicateException {
        agency.addLocation(name,description);
    }

    public void removeLocation(String name)
                throws RemoteException, NotFoundException {
        agency.removeLocation(name);
    }

    public Collection getSkills() throws RemoteException {
        return agency.getSkills();
    }

    public String getSkillDescription(String name)
                  throws RemoteException, NotFoundException {
        return agency.getSkillDescription(name);
    }
    public void updateSkill(String name, String description)
                throws RemoteException, NotFoundException {
        agency.updateSkill(name,description);
    }

    public void addSkill(String name, String description)
                throws RemoteException, DuplicateException {
        agency.addSkill(name,description);
    }

    public void removeSkill(String name)
                throws RemoteException, NotFoundException {
        agency.removeSkill(name);
    }

    public List select(String table) throws RemoteException {
        return agency.select(table);
    }

}

The bean in Listing 13.10 is an example of an adapter (or wrapper) design pattern because it wraps around the agency session bean to simplify using the Session EJB on the JSP.

When deploying the agencyName example, if you add the new Web component to the simple Web application you will need to include the web.agencyBean class file, as well as the JSP. If you create a new Web application, you will also need to add the home and remote interfaces for the agency Session EJB.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.6.10