December 22, 2014
Hot Topics:

JavaServer Pages and JavaBean Components, Part I

  • June 26, 2000
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »


Introduction

What is JSP?

JSP makes it possible to embed Java code fragments into special HTML tags.  A JSP engine automatically creates, compiles, and executes servlets to implement the behavior of the combined HTML and embedded Java code.

Previous Lessons

Previous lessons have explained the use of the following JSP elements:

  • Output comments
  • Hidden comments
  • Declarations
  • Expressions
  • Scriptlets
  • The include directive
  • The page directive
  • The <jsp.forward> tag
This and subsequent lessons will teach you how to use JSP with JavaBean components.

What is a JavaBean Component

The topic of JavaBean components is a broad and complex topic.  I have written several tutorial lessons on the subject that you can view on my onsite at the following URL.  (You might want to bookmark it for future reference.)

An overview

Of necessity, this lesson can provide little more than an overview of the subject of JavaBean components.  You are encouraged to review the tutorial lessons on JavaBean components mentioned above to learn more about the details.

A loose definition

Although this is not a rigorous definition, for this lesson, it should suffice to say that a JavaBean component need not be any more complex than a class that implements the Serializable interface and has a public constructor that takes no parameters.

Make it useful

To be useful, the class should have one or more exposed methods, each of which performs some useful work.

An exposed method in a JavaBean component is any public method.

Other desirable attributes

In the next lesson, I will dig a little deeper into JavaBean components and describe some other attributes that the class should have to make it more useful.

A sample JavaBean component

Figure 1 is a sample JavaBean component that will be used to illustrate the integration of JSP and JavaBean components in this lesson.

As you can see, this Bean implements the Serializable interface.  It also has a noarg constructor by default since no parameterized constructors were defined in the class definition.

The name of the Bean is jspBeanTest001

The name of the Bean is the same as the name of the class:  jspBeanTest001.

The Bean has three exposed methods:

  • setSize()
  • getSize()
  • exposedMethod()
Bean properties

In addition to being exposed methods, the first two of these methods represent the set and get side of the property named size.

Beans design patterns

The names of these two methods satisfy the JavaBean design pattern for properties.  (See my online Java tutorials mentioned earlier for a discussion of properties.)

Why Use Beans with JSP

JSP is powerful

By now you may have concluded that JSP provides a powerful capability, but you probably wouldn't want to create a large, complex Java program using JSP.

Creating large JSP program would be difficult

That would be a difficult task because:

  • The syntax is a little unwieldy.
  • Debugging is very difficult.


The good news

The good news is that you don't need to create large Java programs using JSP for JSP to be useful.  The idea is to use each of the different capabilities of Java for the purpose for which it is best suited.

Mixing executable code and raw HTML

JSP is well suited to mixing executable code fragments and raw HTML (or XML) on a page.

Reusable software components

JavaBean components are well suited to the task of capturing business logic into reusable software components.  These reusable components are potentially large Java programs.

The combination is very powerful

It is the combination of these two capabilities, JSP and Beans, which provides maximum power.

Use Beans for business logic

You should program your business logic as JavaBean components where you have the best access to high-quality editors, compilers, etc.

Use Java fragments to integrate Beans with HTML

Similarly, you should restrict your use of Java code fragments in JSP pages to the invocation of those beans, causing the output from the Beans to be integrated into HTML text streams for transmittal back to the browser.

Creating or Locating an Instance of the Bean

Before you can use a Bean with JSP, you must either locate an existing instance of the Bean class (an object), or you must create a new instance of the Bean class.

You can accomplish this by using the <jsp:useBean> tag.

General Discussion

The <jsp:useBean> tag attempts to locate an instance of the Bean class.  If no such object exists, the tag causes a Bean object to be created.  Creation can take either of two forms:

  • Instantiation from the Bean class.
  • Reconstruction from a previously serialized Bean object.
Here are the steps

According to Sun, in order to locate or create a Bean, the <jsp:useBean> tag takes the following steps in order:
 

1.Attempts to locate a Bean with the scope and name you specify. 
2.Defines an object reference variable with the name you specify. 
3.If it finds the Bean, stores a reference to it in the variable. If you specified type, gives the Bean that type. 
4.If it does not find the Bean, instantiates it from the class you specify, storing a reference to it in the new variable. If the class name represents a serialized template, the Bean is instantiated by java.beans.Beans.instantiate. 
5.If it has instantiated (rather than located) the Bean, and if it has body tags (between <jsp:useBean> and </jsp:useBean>), executes the body tags. 

Details, details!

In order to understand all of the above details, you will need a deeper understanding of JavaBean components than you will get in this lesson.

Reusable software components

However, JavaBean components are reusable software components.  One of the great benefits of using JavaBean components is that you don't have to understand all of the details in order to use them to advantage.

What do you really need to understand?

As a practical matter, all that you really need to know about JavaBean components in order to use them with JSP is to where to put the class files on your server, and how to reference them using the syntax that I provide below.

Of course, you also need to understand the behavior of the Bean, but that is assumed to be a given.

What about enterprise beans?

If you already know about enterprise beans, this may be of interest to you.  Otherwise, skip to the next section.

JSP 1.0 does not work with enterprise beans.  If you want to use enterprise beans, you can write a JSP file that constructs a JavaBean component, and have the JavaBean component call the enterprise Bean.

Element Syntax

Here is the JSP element syntax for creating or locating an instance of a Bean:

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

I will discuss some of the attributes of the tag in the next section.

Attributes of the <jsp:useBean> Element

id="beanInstanceName"

The purpose of this attribute is to name a variable that identifies the Bean.  You can reference this variable later in expressions or scriptlets in the same JSP file.

This variable name is accessible within the scope that you identify as explained below.

A sample variable

The sample JSP page later in this lesson will use the following value for this attribute:

id="theBean"

Case sensitivity

The variable name is case sensitive, and must be a valid name in the Java programming language.

Matching earlier definition

It is possible that the Bean has already been created by an earlier <jsp:useBean> tag.  In this case, the value of id must match the value used in the original <jsp:useBean> tag.

scope="page | request | session | application"

The purpose of this attribute is to define the scope in which the Bean exists.  This also defines the scope in which the id described above is accessible.

The choices are page, request, session, or application.  I will refer you to my tutorial lessons on servlets for a better understanding of what these choices mean.

The default is page

Even though the default value is page, the sample JSP page discussed later in this lesson uses the following attribute value to illustrate the syntax.

scope="page"

class="package.class"

This attribute causes a Bean to be instantiated from a class, using the new keyword and the class constructor.

The class must not be abstract, and must have a public constructor that takes no arguments.  Both the package and class name are case sensitive.

Sample instantiation

The sample JSP page that I discuss later in this lesson uses the following value for this attribute:

class="BaldwinBeans.jspBeanTest001"

class="package.class" type="package.class"

Another option is to instantiate a new Bean object from a class and to specify a type for the new Bean.

In keeping with the general inheritance and polymorphic behavior of Java, the type that you specify can be the same as the class, a superclass of the class, or an interface implemented by the class.

beanName="{ package.class | <%= expression %> }" type="package.class"

Still another option is to instantiate a Bean from either a class or a serialized template, using the java.beans.Beans.instantiate() method.

The use of this attribute also gives the Bean the type specified in type.

type="package.class"

If the bean already exists in the specified scope, this attribute can be use to give the Bean the type you specify.  The choices for type are as described earlier.

Sample JSP Page

Figure 2 shows a JSP file that is designed to use the Bean shown earlier in Figure 1.

The <jsp:useBean> tag, and its attributes, are highlighted in boldface.

This tag either finds or instantiates a Bean object for the Bean class named BaldwinBeans.jspBeanTest001.

Variable named theBean

As mentioned earlier, this tag creates a variable named theBean that can be used to refer to the Bean object in JSP code later in the page.

Page scope

Also, as explained earlier, this tag specifies the scope in which the variable named theBean is accessible, as page.

Invoking methods on the Bean

Three JSP expressions and one JSP scriptlet refer to the bean via the variable named theBean later in the page.  I have colored those references red to make them easy to find.

Exposed methods

In all four cases, one of the exposed methods of the Bean is being invoked.  In the following scriptlet, the String parameter "Large" is passed to the method named setSize() when it is invoked.

Note that the variable named theBean behaves just like an ordinary Java reference variable.

<% theBean.setSize("Large"); %>

Setter method for the property named size

Since the method named setSize() satisfies the design-pattern naming conventions for the setter side of a property, Bean jargon would say that the property named size is being set to the String value "Large".

The getter method

Two of the references to theBean invoke the getter method of the size property.  The getter method is named getSize().

Since these two references are inside a JSP expression, the String values returned by the getter method is written to the output and sent back to the browser that requested the JSP page in the first place.

Ordinary exposed method

Finally, one of the references to theBean invokes an ordinary method named exposedMethod().

This method call is also inside a JSP expression and the String value that it returns is written to the output and sent back to the browser.

The browser output

Figure 3 shows a replica of my browser output for this JSP page.  There aren't any surprises here.

However, when I copied the text from my browser window into this presentation, I colored the text produced by the Bean red to make it easy to spot.  (Note that neither the HTML nor the JSP contained anything to produce red text on the browser screen.)

You should be able to correlate each line of output from the browser window with either raw HTML text in the JSP page, or with the invocation of methods on theBean in JSP expressions.

JSP Syntax Summary

In this and previous lessons, I have discussed the following JSP syntax:

Output comments:
<!-- comment [ <%= expression %> ] -->

Hidden comments:
<%-- hidden comment --%>

Declarations:
<%! declarations %>

Expressions:
<%= expression %>

Scriptlets:
<% code fragment %>

Include Directive:
<%@ include file="relativeURL" %>

Page Directive:
<%@ page
  [ language="java" ]
  [ extends="package.class" ]
  [ import= "{ package.class |
    package.* }, ..." ]
  [ session="true|false" ]
  [ buffer="none|8kb|sizekb" ]
  [ autoFlush="true|false" ]
  [ isThreadSafe="true|false" ]
  [ info="text" ]
  [ errorPage="relativeURL" ]
  [ contentType="mimeType [
    ;charset=characterSet ]" |
    "text/html ; charset=ISO-8859-1" ]
  [ isErrorPage="true|false" ]
%>

jsp:forward tag:
<jsp:forward page=
     "{ relativeURL | <%= expression %> }" />

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

Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without  express written permission from Richard Baldwin is prohibited.
 

About the author

Richard Baldwin is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel