© Copyright Marcus Green 2007

Chapter 8) Building JSP Pages Using Standard Actions

1) Using beans and properties

8.1) Given a design goal, create a code snippet using the following standard actions: jsp:useBean (with attributes: 'id', 'scope', 'type', and 'class'), jsp:getProperty, and jsp:setProperty (with all attribute combinations).

The useBean tag (JSP.5.1)

The term JavaBean is a rather overloaded term in the world of Java as it is used with three related but very distinct purposes. There are Enterprise JavaBeans (EJB) which is the subject of an entire exam syllabus and is not relevant to this discussion. There are graphical JavaBeans which are used to create reusable tools for GUI builders and there are the the type of JavaBeans as used within JSP pages. There is nothing “magic” about a JavaBean, it is just a standard Java class that adheres to a relatively simple naming convention. JavaBeans are used within JSP as a way to make Java objects available within the page and to reduce the need for scriptlets within the page.

One of the common requirements for all types of JavaBeans is that it must be a public non abstract class (i.e. It must be possible to directly create an instance) and it have a public zero argument constructor. The zero argument constructor can be the default one provided by Java if there is not explicitly defined constructor.

The use of JavaBeans within JSP pages is a system for accessing Java components through the standard interface of methods with set and get prefixes.

The general syntax for the useBean tag is as follows.

<jsp:useBean id="myBean" type=”classtype” class="com.mydomain.ClassName" scope="session" />

The useBean tag is define rather neatly in the JSP specification as follows

A jsp:useBean action associates an instance of a Java programming language object defined within a given scope and available with a given id with a newly declared scripting variable of the same id.”

The id attribute is mandatory and can be an arbitrary string, but each can only appear once within a page (i.e. You cannot have two beans with the same id within a page).

The id attribute of a useBean tag is mandatory and can be an arbitrary string, but must be unique within any one page

You can think of the id attribute as standing for identity as it is used by other tags to identify the bean that is being accessed. The actual class must be stored under the

WEB-INF\classes 

directory, i.e. In the example given the path starting with the webapp directory would be

WEB-INF\classes\com\mydomain\Classname.class

The scope attribute

The scope attribute can be page,request,session, or application. The scope attribute is optional and if it is omitted the default is page scope. Thus if the scope is set to sesssion the bean will be visible and usable in other pages until the session becomes invalid. Otherwise the bean effectively ceases to exist once the page has finished executing. The name useBean could be misleading as the action will use an existing instance of the bean or create an instance if none currently exists.

The following is a trivial example of a JavaBean for use within a JSP page.


The scope attribute defaults to page

A useBean example

package com.examulator;
public class Person {
   private String firstName="joe";
   private String lastName="soap";
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getFirstName() {
      return firstName;
   }
    
   public String getLastName() {
      return lastName;
   }
}

That JavaBean can be used within a JSP as follows

<jsp:useBean id="person" type="com.examulator.Person" class="com.examulator.Person" scope="session" />
<html>
<%
   out.print(person.getFirstName());
%>
</html>

If you compile and run that page you will find it outputs the default firstName of joe to the browser. The type attribute can be considered like the reference type in a plain old Java class whilst the class is the type of the actual object.

The getProperty tag

In keeping with the idea of reducing the amount of scriptlet code within JSP pages there is a more elegant way of accessing properties of bean instances by using the getProperty tag, which automatically sends the result of the method call to the output stream. The get property tag has two attributes both of which are mandatory, they are name and property. The name refers to the id of the bean instance and the property refers to the method with the get prefix that is being accessed (you don't include the actual get prefix). The following code illustrates the use of the <jsp:getProperty> tag.

<jsp:useBean id="person" type="com.examulator.Person" class="com.examulator.Person" scope="session" />
<html>
<jsp:getProperty name="person" property="firstName"/>
</html>

The setProperty tag

Another powerful features of the JavaBeans syntax is the use of the setProperty tags. This allows values of a JavaBean to be set at runtime. The following JSP code illustrates this.

<jsp:useBean id="person" type="com.examulator.Person" class="com.examulator.Person" scope="session" >
<jsp:setProperty name="person" property="firstName" value="Marcus"/>
<jsp:setProperty name="person" property="lastName"  value="Green"/>
</jsp:useBean>

<html>
<jsp:getProperty name="person" property="firstName" />
<jsp:getProperty name="person" property="lastName" />    
</html>

Note that if a bean with id of person already exists the setProperty code will not be executed.


If setProperty is nested within a useBean tag, the property will only be set when the bean is created

There might be situations where you only want a bean property value to be set when it is created, not when it already exists. If you can give a good example of this situation, please email me. This can be done by nesting the call to setProperty within the useBean tag. Then the setProperty tag will only be executed when the bean is created and the value will not be re-set if the bean already exists.

The param attribute of setProperty

It is a very common requirement to want to set a property according to a runtime query parameter. Instead of using the value attribute to explicitly set the value, the param tag will automatically substitute a matching query parameter to populate the bean attribute. Thus if the following JSP code is executed with the URL query string

?firstname=marcus&lastname=green

The output will be

marcus green

<jsp:useBean id="person" type="com.examulator.Person" class="com.examulator.Person" >
<jsp:setProperty name="person" property="firstName" param="firstname" />
<jsp:setProperty name="person" property="lastName"  param="lastname" />
</jsp:useBean>

<html>
<jsp:getProperty name="person" property="firstName" />
<jsp:getProperty name="person" property="lastName" />    
</html>
<html>
</html>

Default Parameters

If you think about the logic of having the standardised method/attribute naming convention that JavaBeans provides it should become obvious that it is possible to automatically the settings of attributes to the names of query string parameters passed to the page. Thus for instance you can deduce that a parameter with a name of firstName in the HTTP query string should be mapped to set the attribute of a bean to the setFirstName method call (or you can think of it as the firstName attribute of the bean).

The mechanism for performing this automatic mapping of query parameters to bean attributes is to use a the * wildcard for the property attribute of the setProperty tag. Thus if you call the following JSP page with the HTTP query

?firstName=marcus&lastName=green

<jsp:useBean id="person" type="com.examulator.Person" class="com.examulator.Person" >
<jsp:setProperty name="person" property="*"   />
</jsp:useBean>

<html>
<jsp:getProperty name="person" property="firstName" />
<jsp:getProperty name="person" property="lastName" />    
</html>
</html>

It will correctly map the firstName and lastName parameters to the person bean, which will cause the getProperty calls to output

marcus green

The type attribute

The type attribute is optional and much of the time you will not need to specify this value so make an extra effort to become familiar with its use for the purposes of the exam. The type of a reference may be different to that of the object. Thus you may recall from the Collection class objective of the SCJP that you can declare a HashMap as being of the Map interface type thus

    java.util.Map m = new java.util.HashMap();

In a very similar way the type attribute allows you to explicitly declare the type of the reference. Thus if the Person class was a child of a class called com.examulator.Record you could declare a bean as follows

<jsp:useBean id="person" type="com.examulator.Record" class="com.examulator.Person" scope="session" />


The type attribute sets the type of the reference which points to the class object.

This is the equivalent of declaring

com.examulator.Record person = new com.examulator.Person();

The type attribute must be compatible with the class, e.g. It can be an interface that is implemented by the class or a concrete or abstract class that is extended by the class.

Using type without class

It is possible to have a useBean statement that has the type attribute without the class attribute providing the attribute already exists in the scope and with the id you put in the tag. If those conditions are not met an exception will be thrown. For “real world” programming you will almost always use the class attribute with class, but this is not the real world, this is exam world, so read that key concept and perhaps even write it down a few times to make sure you know it.

The type attribute can be used without class, but unless an instance exists an exception will be thrown

The beanName attribute

The JSP specification says the following about the beanName attribute

The attribute beanName specifies the name of a Bean, as specified in the JavaBeans specification. It is used as an argument to the instantiate method in the java.beans.Beans class. It must be of the form a.b.c, which may be either a class, or the name of a resource of the form a/b/c.ser that will be resolved in the current ClassLoader.”

The key to that fantastically opaque explanation is the extension ser where it says a/b/c.ser. The beanName attribute can be used to point to a file that contains a serialized bean (the extension .ser is used to indicate a serialized object). However when using beanName with a serialized file the .ser extension is not included. The advantage of beanName over class is that the the value can be specified at requestion-time unlike class which must be specified at translation time. A useBean tag can use either class or beanName but not both. A beanName attribute must always be accompanied by a type attribute.


Other sources

The useBean syntax according to Sun
http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html

According to Mikalai Zaikin
http://java.boot.by/wcd-guide/ch08.html