Using Java Beans with JSPs

The JSP specification enables you to include JavaBeans, which are different from the Enterprise JavaBeans discussed later in this book. JavaBeans encapsulate presentation logic or rudimentary business logic in your pages. By encapsulating logic in a JavaBean, you can keep your Web developers from accidentally compromising or corrupting your Java code. JavaBeans help you create more maintainable pages.

Integration of JavaBeans with JSP pages is done through the use of three JSP actions. Let's take a look at each of these tags and how to use them.

JSP Tags for Using Beans

The <jsp:useBean> tag enables a JSP developer to specify a JavaBean to be included in the JSP page. This tag tries to instantiate a JavaBean, and gets any parameters that are specified. There are three major parameters that affect the capability of the container to instantiate your JavaBean. These are: the scope of the JavaBean, an ID field that represents the bean's name as it should be referenced in your application, and the class name of the JavaBean. The following is a simple example of this tag:

<jsp:useBean id="mybean" class="com.myco.myapp.mybean"
scope="page">
</jsp:useBean>

It is a best practice to use packages for your JavaBeans. If a class is not assigned to a package, then it is not available unless it is explicitly imported into a class that does exist in a package. If you do not specify a package, it is more likely that you can run into errors that are difficult to diagnose.


The following is the complete syntax for this tag:

<jsp: useBean
id=" beanInstanceName "
scope=" page |request| session| application"
{ class=" package. class " |
  type=" package. class " |
  beanName=" { package. class | <%= expression %> } "
{/>| > other tags </ jsp: useBean> }

There are a number of possible attributes for the useBean tag:

  • id— Represents the bean's name as it should be referenced in your application, and the class name of the JavaBean. This is the name your Java code in the JSP page uses to access the JavaBean instance.

  • class— Specifies the complete class name representing the JavaBean. It does not include the class extension. For example: com.myco.myapp.mybean.

  • scope— Specifies the scope in which the JavaBean is available. There are four different possible values:

    • page— The JavaBean is available for the current page. Your JavaBean is discarded upon completion of the current request for your JSP.

    • request— The JavaBean is available from the current page's ServletRequest object. This is useful when you forward or include another JSP page using the page directives described earlier in this chapter. You can use the getAttribute(name) method on the ServletRequest object to locate a reference to the JavaBean in the forward or included pages.

    • Session— The JavaBean is available for the duration of the user session. It is available from the current page's HttpSession object.

    • Application— The JavaBean is available indefinitely and is stored in the current page's ServletContext object as defined for Web applications. To access the JavaBean, use the getAttribute(name) method on the ServletContext object.

  • Class— The fully qualified name of the class that defines the implementation of the object. The class name is case sensitive.

  • BeanName— The name of a JavaBean.

If you include the useBean tag in your JSP page, the WebLogic Server container automatically creates an instance of that bean. And depending upon the scope of that bean as specified by the tag, it is available to your JSP page or to the entire session. WebLogic Server automatically handles the disposal of the bean.

Building a JavaBean into a JSP

Let's say we have a user name and some data associated with that user name in a remote location such as a database or a text file. This data could be, for example, the user's employee ID and Social Security number.

We first create a JavaBean to get the user ID and other data. Then, we access the data by calling methods in the JavaBean from two JSP pages. The first JSP page has a form for input of the user name. Form results are posted to another JSP page, which handles the form and makes the appropriate calls to the JavaBean.

Creating a JavaBean

First, let's specify the JavaBean that encapsulates the logic required to get the user and the data associated with that user:

package com.mypackage;

public class UserDataBean {

You must also specify a default constructor. This constructor method is called when the JavaBean object is created:

// The default constructor.
public UserDataBean ()
{
}

If we want to put the JavaBean in an HTTP session so that it can take advantage of clustering, the JavaBean must be serializable for all components that are placed into the HTTP session. In this case, the class declaration would look like this:

public class UserDataBean implements
Serializable

Serializability of a class is enabled when the class implements the java.io.Serializable interface. It is a key component for HttpSessions clustering.


Next, define methods that are called by a JSP page to get the values that we want. The following method takes the user name and returns the user ID number:

public int getID()
{
     /*
In the real world, code would go off to another resource such as
a database or an Enterprise JavaBean to locate the ID that goes
with the name provided.  In this case, we simply provide a dummy
ID that is returned no matter what name we receive.
*/
return 7;
}
This method takes the user name as a parameter and returns the
user Social Security number:
public void setID(int ID)
    {
    /*
In the real world, code would go off to another resource such as
a database or an Enterprise JavaBean to set the ID that goes with
the name we are provided.  In this case, we simply provide a
dummy SSN that is returned no matter what name we receive.
*/
    }

The JSP Form Page: form.jsp

A JSP form page can contain a field for users to input a user name. The user name value can then be posted to another JSP page.

<!doctype html public "-//w3c/dtd HTML 4.0//en">
<html>
<head>
    <title> Enter User Name</title>
</head>
<body>

Next, define a form that posts to the JSP page that uses our JavaBean:

<FORM action="beanuser.jsp">
Enter Name: <INPUT type="text" size="30"
name="Name">
 <input type=submit value="Submit">
<FORM>

Finally, finish off the HTML page by closing off the HTML tags:

</body>
</html>

The output of this JSP page might look like Figure 4-3.

Figure 4-3. Form for Entering User Name


To view the form, copy it into the default Web applications directory, as you did before. The viewer of this page enters a user name and clicks the Submit button. This results in a POST to the page named beanuser.jsp.

The beanuser.jsp Page

The beanuser.jsp page takes the user name entered in form.jsp and uses that to make calls into the UserDataBean JavaBean created earlier. Build beanuser.jsp using the script provided.

We need to specify the JavaBean. In this case, we set the ID of the bean (the name we use to reference the bean in our JSP page) to be equal to "OurBean". We also set the scope of the JavaBean to be equal to "page", meaning that it persists only for the life of the page. Finally, we specify the Java class to be loaded:

<jsp:useBean id="OurBean"
    scope="page"
    class="com.mypackage.UserDataBean"
/>

Set the typical HTML header information:

<!doctype html public "-//w3c/dtd HTML 4.0//en">
<html>
<head>
    <title>Using Bean</title>
</head>
<body>

<h1>Using Bean</h1>

Next, call methods on the JavaBean and print out the results:

<%
String userName = request.getParameter( "Name" );
out.print(OurBean.getSSN(userName));
out.print(OurBean.getID(userName));
%>

Finally, finish off the HTML page:

</body>
</html>

When viewing this set of pages, a user first sees the form.jsp page in the Web browser (see Figure 4-4).

Figure 4-4. The form.jsp Page


After entering the user name, the beanuser.jsp page is executed (see Figure 4-5).

Figure 4-5. Output from the JavaBean


Running the JavaBean Example in WebLogic Server

To deploy the basic JavaBean example, databean.war, first be sure that you have installed BEA WebLogic Server 6.0. Start the default server; then do the following:

1.
Locate the databean.war code on the CD included with this book. It should be located in the directory titled examplesch4 under the root directory of the CD.

2.
Copy this file from the CD into the applications directory of your BEA WebLogic Server 6.0 installation. If you are using Microsoft Windows, you can use the Windows Explorer or the command line to copy this file. Depending upon the location of your installation, the directory path should look something like the following:

c:eawlserver6.0configmydomainapplications

3.
The Web application is now installed. You can view it by opening a Web browser and viewing the following URL: http://127.0.0.1:7001/databean/.

Note: If you have an HTTP proxy enabled in your Web browser, as many organizations require, you may need to disable it.

WebLogic Server includes the option to show debugging information in the window running it. This can be very useful when trying to determine why your application is not performing as expected. To turn this on, start your WebLogic Server console. Then, click on the navigation panel to the left to locate information for the server for which you want debugging information. Once you find the appropriate server, such as “myserver”, information specific to that server should appear on the right side of the Web browser. Click on the Logging tab, set a severity level such as “info”, and then click the check box next to the Debug to Stdout option (see Figure 4-6).

Figure 4-6. Enabling Error Logging to the WebLogic Server Startup Window


The next time your instance of WebLogic Server starts, you are presented with a voluminous amount of information about everything going on (see Figure 4-7).

Figure 4-7. Logging Output to the Startup Window


The databean.war Example Components

The databean.war is a complete Web application that includes all the necessary components required by the Java specifications. The most notable of these components is the WEB-INF/ directory. As mentioned in Chapter 3, the WEB-INF directory holds the configuration and deployment information for the Web application. Objects such as JavaBeans are also stored in this directory. These components are not available directly to clients of the Web application.

Configuration information for the Web application is contained in the web.xml deployment descriptor file. This includes information for the WebLogic Server deployment to recognize what components are included in the Web application and what settings they should have. A comprehensive description of how to create these deployment descriptor files is included with the WebLogic Server documentation at

http://e-docs.bea.com/wls/docs60/programming/webappdeployment.html.

Similar documentation exists for other JSP engines. Consult your individual product documentation because many application servers slightly differ from the specification in this area and have added application server–specific extensions.

The JavaBean classes themselves are kept in the WEB-INF/classes subdirectory. The application server looks for JavaBean code in this directory.

Building the JavaBean Example in WebLogic Server

To build and deploy the basic JavaBean example, databean.war, you can use the included Microsoft Windows build script.

Once the server is started, do the following:

1.
Locate the databean.war file on the CD included with this book. It should be located in the directory titled examplesch4databean under the root directory of the CD.

2.
Copy this file into an empty directory that you will use for code development on your PC. For this example, we use the directory c:dev.

3.
The Web application code is now copied over. We need to unpack it using the jar utility included with WebLogic Server. First, make sure that you have your environment set correctly. Start a command shell and run the setEnv.cmd script that is included as part of the WebLogic Server installation. In most cases, this is located at:

c:eawlserver6.0configmydomainsetEnv.cmd

This sets the environment so that you can access all WebLogic Server utilities from the command line (see Figure 4-8).

Figure 4-8. Output from Running the setEnv.cmd Script


The screen shot in Figure 4-8 shows WebLogic Server installed on the C: drive. Your installation may be on another drive.

4.
Navigate to your development directory (for example, c:dev), and unpack the war file with the jar command:

jar xvf databean.war

You should see something that looks like Figure 4-9. Note that unpacking the .war file creates the META-INF and WEB-INF directories, plus any subdirectories:

Figure 4-9. Output of the jar Command


5.
A batch file (build.bat) is included in the .war file. This would not have been done in a standard .war file because any file in that .war file would be available, once the Web application is deployed, to anyone with a Web browser. For the sake of simplicity, all the files are included in this single .war.

6.
Now, edit build.bat with your favorite text editor. You may need to change the first line of the script to point to the location of your WebLogic Server's applications directory.

7.
Execute build.bat from the command line by typing “build.bat” (see Figure 4-10).

Figure 4-10. Results of Running build.bat


The build script has set the deployment directory (in this case) on the C: drive. Next, it attempts to delete any existing installation of this .war file. Then, it compiles any Java classes and places them in the classes directory. Finally, it uses the jar command to create a final package and places that in the applications directory.

In the window running the WebLogic Server, you should see something like this each time you run the script, if you have turned on debugging for the server in the WebLogic Server console:

<Nov 24, 2000 11:16:17 AM PST> <Info> <J2EE> <Undeployed :
databean>

<Nov 24, 2000 11:16:17 AM PST> <Info> <J2EE> <Deployed :
databean>

This indicates that the component has been deployed or undeployed. To view the deployed component, point your Web browser to http://127.0.0.1:7001/databean/.

Note: If you have an HTTP proxy enabled in your Web browser, as many organizations require, you might need to disable this to access your own machine as a Web server.

Using JavaBean Properties

Properties allow for convenient setting and retrieving of parameters in a JavaBean. They are useful for streamlining the retrieval of values in a JavaBean. One intended benefit of properties lies in the promise of off-the-shelf JavaBeans, which are configured when they are employed in your JSP page. In reality, off-the-shelf JavaBean components have not really proven to be viable in the J2EE marketplace.

How Properties Work

The <jsp:useBean> tag lets the JSP developer set properties in a given JavaBean. These tags are actually embedded in the <jsp:useBean> tag at instantiation time to pass properties into the JavaBean. A simple example of property setting is as follows:

<jsp:useBean id="mybean" class="com.myco.myapp.mybean"
scope="page">
<jsp:setProperty name="mybean" property="gumby" value="999">
</jsp:useBean>

This instantiates a bean with ID "mybean" with a scope of one page if the bean does not already exist. It also sets a property named "gumby" with a value of 999. The full syntax of this tag is as follows:

<jsp:setProperty name=" beanName" prop_expr />
prop_expr ::= property="*" |
property=" propertyName"|
property=" propertyName" param=" parameterName"|
property=" propertyName" value=" propertyValue"
propertyValue ::= string

It is also possible to have all bean properties transparently populated from the HTTP request parameters. A complete example of this is included later in this chapter.

The <jsp:getProperty> Tag

The <jsp:getProperty> tag allows a JSP page to query a JavaBean for a given property. It is the opposite of the setProperty tag. getProperty puts the value of the property in the JSP's out object for display back to the client.

The following is a simple example using this tag that queries the mybean JavaBean for the value of the property equal to the name gumby :

<jsp:getProperty name="mybean" property="gumby" />

The full syntax of the tag is:

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

The name is the name of the JavaBean, and property is equal to the property name that is to be retrieved. getProperty can be used anywhere in a JSP page.

This tag is very useful because it enables us to replace the following Java expression:

<%
out.print(OurBean.getID());
%>

with a simpler form:

<jsp:getProperty name="OurBean" property="ID" />

In the preceding example, the JavaBean named "OurBean" has a property named "ID".

Note that problems in instantiating your bean cause exceptions to be thrown by JSP. You should always specify an error page in your original page declaration as noted earlier in this chapter.


Building a Bean to Use Properties

To build a JavaBean to support properties, first use a JSP to reference the JavaBean:

<jsp:useBean id="mybean"
class="com.myco.myapp.mybean" scope="page">
<jsp:setProperty name="mybean" property="gumby" value="999">
</jsp:useBean>

Note that this JavaBean has a property named "Gumby" that we set to a value of 999. To support this in our JavaBean we must add two methods: a “getter” and a “setter.” They look like this:

public String getGumby() { };
public void setGumby(String a);

The full format of these two methods is:

public < PropertyType> get< PropertyName>();
public void set< PropertyName>(< PropertyType> a);

First, you have a method that is used to retrieve the value of the property that is defined by simply putting the keyword get in front of your property name. Similarly, a method used to set the value of the property inside of the bean is the name of the property prefaced by the word set.

The full JavaBean would be:

package com.myco.myapp;

public class mybean
{
    private String gumby;

    public void setGumby(String newGumby )
    {
        gumby=newGumby;
    }

    public User getGumby()
    {
        return gumby;
    }
}

You can use more complex types for property values, including user-defined classes, and types such as booleans and integers.

Case is significant: Note that getGumby() and setGumby() access the variable gumby, not Gumby. Using the wrong case is a common mistake that can result in some very strange errors.


Automatically Populating JavaBean Properties

The most powerful use of JavaBeans is when they are automatically populated with request parameters. To explain, requests contain parameters such as those included in a Web form. Each of these parameters contains a name and a text value. The JavaBean model with JSPs allows for a JSP with the appropriate get<name> and set<name> methods to be automatically filled.

This is accomplished by using the <jsp:setProperty name="beanName" property="<property expression>"/> tag, where <property expression> is an expression representing all properties to be set. For example, “*” is the regular expression meaning “all properties.” It is not possible to have a regular expression like foo*, meaning all properties whose names begin with the letters foo such as foobu and foobar.

Suppose we have an HTML page that includes the following form:

<FORM action="beanuser2.jsp">
Enter Name: <INPUT type="text" size="30"
name="Name">
 <input type=submit value="Submit">
<FORM>

This is the same form that we specified in previous sections in this chapter. It includes a text field that takes a user name. The field has a size of 30 characters, and the value is stored in the request parameter named "Name".

We can then build the following JavaBean. It includes a private value, called myName, which is used in the JavaBean to keep the name value. It also includes two methods, getName and setName, which are used to retrieve this name value and set the name values, respectively:

Package com.mypackage;

public class MyNameBean {

  private String myName;

  /*
    The default constructor.
  */
  public MyNameBean ()
  {

  }

  public String getName()
  {
    /*
      In a real application, code that would do some
      work would be located here.
    */
    return myName;
  }

  public void setName(String InName)
  {
    myName=InName;
  }
}

beanuser2.jsp

The beanuser2.jsp page receives the user name entered in form.jsp. Unlike the original beanuser.jsp, it uses useBean to automatically populate the bean parameters.

<%@ page import="com.mypackage.*" %>

<jsp:useBean id="myNameBean"
    scope="page"
    class="com.mypackage.UserDataBean"
    property="*"
/>

<!doctype html public "-//w3c/dtd HTML 4.0//en">
<html><head>
<title>Using Bean</title>
</head><body>

<h1>Using Bean</h1>
<jsp:getProperty name="myNameBean" property="Name" />
</body></html>

A complete example of automatic population of JavaBeans with submitted form values is included as part of the WebAuction application.


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

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