What are JavaBeans from a JSP? How to install them? - JSP

You can use JavaBean components in a JSP by using JSP language elements. For example, there are tags that enable you to create and initialize a JavaBean from a JSP.There are also JSP tags for getting and setting the properties of a JavaBean. Because a JSP can create and use an object of any valid Java type from inside a JSPdeclaration tag or a JSP scriptlet tag, you might question why you would need a separate set of tags to use JavaBean from the JSP.The answer is that the JSP tags lend themselves to creating much more readable, concise JSPs than using declarations and scriptlets. Another benefit is that it leads to a separation of content from code.

Using JavaBeans from JSP with Standard Action Elements

The standard action elements that are predefined for use in a JSP are jsp:useBean, jsp:setProperty, and jsp:getProperty.These tags are defined in the following two subsections: “Instantiating JavaBeans from a JSP” and “Accessing and Setting JavaBean Properties from a JSP.”

Instantiating JavaBeans from a JSP

The jsp:useBean tag exists to enable you to write JSPs that make use of JavaBean classes.The tag enables you to instantiate JavaBeans, use JavaBeans, and assign names to them. The syntax of the jsp:useBean tag can take several slightly different forms.The simplest of these is

<jsp:useBean id=”bean_name” class=”fully_qualified_Classname” />

The JavaBean is only instantiated if it does not already exist.This is covered in detail later in this chapter. One thing to be aware of is that the syntax of the jsp:useBean tag follows the production rules of elements and attributes in XML. That is, the element and attribute names are case sensitive, and the attribute values must be enclosed in either single or double quotes. Also, do not forget to close the jsp:useBean tag using either the shorthand XML form (<... />) or the longhand form that uses a separate close tag (</jsp:useBean>). Note that you do not need to specify an XML namespace declaration that binds the jsp prefix to a URI. The forms that the jsp:useBean can take are shown in Table For each form, the scope attribute is optional, and it defaults to page scope if omitted. As you will see later, the jsp:useBean tag has an optional body.

What are JavaBeans from a JSP? How to install them?What are JavaBeans from a JSP? How to install them?

The jsp:useBean tag instantiates the named class using the no-argument constructor. If his constructor is not available, the Web container will be unable to generate the servlet for the JSP. To see the predefined tags in action, you will now see a simple example that uses two JSPs: one JSP to instantiate the Book class from earlier in this chapter, and the other JSP to access its properties.The example will begin by using scriptlets to instantiate the JavaBean, and expression tags to retrieve the values of properties.The example pages are then converted to use the predefined tags, and you will be shown the important parts of the generated servlets. Consider the JSP in Listing There are three parts to the JSP: a page directive, a scriptlet, and some HTML code. It starts by using the page directive to import the Book class. After the page directive, the JSP uses a scriptlet that checks to see if there is a JavaBean bound to the name myBook already instantiated in the session. If not, it creates one and stores it in the user’s session. In this example, the fact that the Book JavaBean is session-scoped means that it can be accessed from other JSPs that are visited by the client.The third part of the JSP is the HTML code that sets up a hyperlink to a second JSP that accesses the JavaBean that was instantiated.

A JSP That Uses Embedded Java Code (1) (useBean1_scriptlet.jsp)

Listing A JSP That Uses Embedded Java Code (1) (useBean1_scriptlet.jsp)

The second JSP in this example is shown in Listing The content of the JSP is fairly self-explanatory. Again, there are three parts: a page directive, a scriptlet, and the HTML code. The JSP begins with the page directive that imports that class for the Book.The page directive is followed by a scriptlet that obtains a reference to the JavaBean that was instantiated on the first page.

A JSP That Uses Embedded Java Code (2) (useBean2_scriptlet.jsp)

Listing A JSP That Uses Embedded Java Code (2) (useBean2_scriptlet.jsp)

Error checking has been omitted for the sake of clarity.In practice, you would normally perform a check at this point to make sure that a value of null has not been returned by the session.getAttribute() method; otherwise, the page will fail further down when the reference is used to access properties of the JavaBean. You can invoke the methods of a JavaBean directly by using either a scriptlet or an expression tag.The syntax is exactly the same as for invoking a method on any other Java object, even the predefined page variables such as page and session. All you need is a reference to the JavaBean, and the name of the method that you want to invoke. For example, using a scriptlet you might write something like

<% shoppingCartBean.displayContents(); %>

When the reference to the shared JavaBean has been acquired, the expression tags within the HTML code access the four properties id, title, author, and price. The output from the JSP in Listing 6.3 is shown in Figure Due to the fact that the no-argument constructor for the Book class is empty, the properties displayed are the initial values for any constructed Java object.That is, zero for numeric types, null for object references, false for boolean variables, and the null character for variables of datatype char.

Figure A JSP that uses embedded Java code.

A JSP that uses embedded Java code

The problem with the JSPs in Listings and is that they require knowledge of the Java programming language to write the scriptlets and expression tags. The example JSP in Listing is rewritten in Listing to use the useBean tag.The JSP begins with the useBean tag and its attributes.The id attribute’s value is the nameof the reference to the JavaBean. In this case, the name of the reference is myBookBean.The class that is used to instantiate the JavaBean is com. conygre. jspdevhandbook. chapter. Book, and theJavaBean’s scope is set to session.The scope attribute has been added so that the declared JavaBean is visible on other JSPs that the user visits.

A JSP That Uses the useBean Tag (1) (useBean1.jsp)

Not only is the useBean tag more readable, but it is less work and there is no Java code in sight!

When it has been translated into a servlet, the important lines of code look something like those shown in Listing

The Generated Servlet for Listing

The code that queries the pageContext object for a session-scoped object bound to the name myBookBean is myBookBean= (com. conygre. jspdevhandbook. chapter. Book) pageContext. getAttribute(“ myBookBean”, PageContext. SESSION_ SCOPE);

If the object cannot be located, then a new one is created with this code:

Any problems encountered at runtime, when the Web container tries to instantiate the JavaBean, are handled by the two catch blocks. If the JavaBean class cannot be located when the application is running, a ClassNotFoundException is thrown by the Java runtime and handled by the first catch block. If there is any other problem instantiating the JavaBean, for example, when a no-argument constructor cannot be found, the second catch block deals with that. The new object is bound into the user’s session by the final line of code:

pageContext.setAttribute(“myBookBean”, myBookBean, PageContext.SESSION_SCOPE);

Accessing and Setting JavaBean Properties from a JSP

There are two predefined tags that are available to access and manipulate the properties of a JavaBean: jsp:getProperty and jsp:setProperty.

The jsp:getProperty Tag

The jsp:getProperty tag enables you to retrieve the value of a property in a JavaBean, and embed it into the output. Its syntax is

<jsp:getProperty name=”bean_name” property=”property_name” />

With this knowledge, the second JSP (Listing ) in the example can be rewritten.The new version is shown in Listing
Listing A JSP That Uses the getProperty Tag (useBean2.jsp)

Listing A JSP That Uses the getProperty Tag (useBean2.jsp)

If you refer back to Listing , you will see that the page directive to import the Book class and scriptlet that retrieved the JavaBean instance from the user’s session, have both been omitted from Listing 6.6.They are both rendered unnecessary by the jsp:getProperty tag.

The code that is inside the HTML table tag in Listing accesses the four properties of the JavaBean. Behind the scenes, the jsp:getProperty tag is implemented using the standard Java Reflection API.That is, for a property whose name is id, the Web container translates the jsp:getProperty tag into Java code that looks for an accessor method called getId(). If you try to access a property that is not defined, the JSP is translated into a servlet, but the Web container generates an error when the servlet is executed. The important lines from the generated servlet’s _jspService method are shown in Listing .

Listing The Generated Servlet for the JSP in Listing

A few things are happening for each out.print method invocation:

  • The JavaBean is located using the pageContext.findAttribute() method.
  • The JspRuntimeLibrary.handleGetProperty() method takes two parameters. The first is the JavaBean located in the previous step, and the second is the property of interest.This is where the Java Reflection API is used to locate and invoke the correct accessor method.
  • The retrieved property value is then converted to a String by the JspRuntimeLibrary.toString() method.

When viewed in a Web browser, the output from Listing 6.6 looks like that shown in Figure . Notice that the three String values for the id, author, and price properties appear to be missing from the table.This is because of the way that the JspRuntimeLibrary.toString() method works. Rather than pass back a value of null, the JspRuntimeLibrary.toString() instead returns an empty string.

The jsp:setProperty Tag

To finish off the example, it would be nice if we could set values for the properties of the Book JavaBean.You can use the jsp:setProperty tag to do this, the basic syntax is

Figure A JSP that uses the getProperty tag.

A JSP that uses the getProperty tag

By the time that you have read this chapter, you will have seen all the different forms that the jsp:setProperty tag can take.The name attribute is mandatory, but can be accompanied by a variety of other attributes, which are listed in Table
Table Forms of the jsp:setProperty Tag

You can use the jsp:setProperty tag anywhere in a JSP, but here it is embedded inside the jsp:useBean tag where it can be used to provide initial values for the JavaBean.This idea is revisited later in this chapter when the concept of scope has been discussed.Consider the JSP in Listing .

Listing A JSP That Uses the useBean and setProperty Tags (useAndSet1.jsp)

Even though the setProperty tags are child elements of the useBean tag in this example, don’t be confused into thinking that they somehow cause the Web container to search for a constructor that takes arguments matching the specified values.The no-argument constructor is still called, and then the correct set method is called for each property. This becomes obvious if you do not nest the setProperty tags inside the useBean tag—you still get the same result. The JSP from Listing translates to a servlet whose _jspService method contains code similar to that shown in Listing .

Listing _jspService Method for the JSP in Listing

The lines of code in the synchronized block are similar to the example in Listing However, the new lines are the ones that follow.The _jspx_specialmyBookBean variable is used to indicate whether the myBookBean JavaBean has been created (or whether it already existed in the user’s session). If the JavaBean has just been created (inside the if statement in the synchronized block), and the _jspx_specialmyBookBean variable has a value of true, the contents of the if statement after the synchronized block are executed.

The JspRuntimeLibrary.introspecthelper() method is used by the generated servlet to set the properties of a JavaBean; it takes six parameters.The first three are of interest and are a reference to the JavaBean, the property name, and the new property value.The latter three parameters are the servlet request, response, and a boolean that indicates whether to throw an error if a set method cannot be located for the specified property.You can see this method used to set values for the four properties of the Book JavaBean.These lines of Java code that use the JspRuntimeLibrary.introspectHelper() method correspond to the jsp:setProperty tags of Listing You might be wondering how a string value is converted into the correct type for a given property.The JSP container uses the valueOf method from the relevant wrapper class for each of the following datatypes: boolean, byte, short, int, long, float, and double. For example, the java.lang.Double.valueOf(string s) method is used to convert a string to a double.This value can then be passed as an argument to the relevant setter method.The other two datatypes that are supported for conversion purposes are java.lang.Object and char. For Object, a new String object is instantiated that contains the value specified in the jsp:setProperty action. For char, the String.charAt(0) method is used.

TheJSTL c:set and c:out Actions

As you saw in Topic,“The JSP Standard Tag Library,” you can use the JSTL c:set action in order to set the value for a target object’s property. Here is the syntax:

The value of the target attribute must evaluate to a JavaBean that has a setter method for the specified property name and value. For example,

Alternatively, you can specify a java.util.Map object as the target, rather than a JavaBean. You also saw the c:out action in Topic,“The JSP Standard Tag Library,”.You can use it instead of the jsp:getProperty action in order to output the value of a JavaBean’s property. For example,

<c:out value=”${sessionScope.myShoppingCart.numberOfItems}” />

The jsp:useBean Tag and Existing JavaBeans

Now that you have seen the jsp:useBean, jsp:getProperty, and jsp:setProperty tags, it is time to consider what happens when your Web application has multiple JSPs that declare the same JavaBean.When a JSP that contains a useBean tag is viewed, it is possible that the JavaBean in question already exists. For a useBean tag such as

<jsp:useBean id=”myBook” class=”com.conygre.jspunleased.chapter6.Book” scope=”session” />

the following happens. First, the Web container searches for a JavaBean with the id myBook that is stored in the predefined session object. If the JavaBean is found, the new id is simply initialized to point to the existing JavaBean. Remember that the new id is a local variable of the generated _jspService() method.The code that performs the lookup in _jspService() looks like this: ...

Thus, there is no problem if an application needs to instantiate more than one JavaBean of a particular type to different ids. If such a JavaBean cannot be located, the Web container makes an attempt to load the com.conygre. jspdevhandbook. chapter. Book class and instantiate a JavaBean from it.

The JavaBean is then bound to the specified id and stored in the appropriate scope.The important part of the jspService() method looks like this:

If the JavaBean has been created, the body of the jsp:useBean tag is then processed. Note that if the JavaBean already exists and is located, that the body of the jsp:useBean tag is not executed. Earlier in this chapter, it was noted that the jsp:useBean tag always uses the default constructor when instantiating a JavaBean. From a certain point of view, you can imagine the jsp:useBean tag and any jsp:setProperty tags within it as combining to simulate a constructor that takes arguments.This is because the body of the jsp:useBean tag is only executed the first time, when the JavaBean is created. This can be seen from the examples in Listings 6.10 and 6.11. Listing 6.10 defines the first JSP in this example. It creates a session-scoped JavaBean, and gives a hyperlink to a second JSP (Listing 6.11) that redeclares the JavaBean.

Listing 6.10 A JSP That Declares a session-scoped JavaBean(beanAlreadyExists.jsp)

Listing 6.10 declares an instance of the com.conygre.jspdevhandbook.chapter6.Book class, and assigns it the name myBookBean. Because this is the first page in the example, the JavaBean does not yet exist, therefore, the Web container will not be able to locate it. The Book class is loaded, the JavaBean instantiated, then the author property is set to the value Mark.This is all done with the following lines of code:

When the user clicks the hyperlink, he is redirected to the JSP in Listing 6.11.

Listing 6.11 A JSP That Redeclares a JavaBean (beanAlreadyExists2.jsp)

Listing 6.11 starts by declaring a JavaBean with the same name and scope, so the Web container simply locates the existing JavaBean instance.The important lines of code from the generated servlet’s _jspService method are

The first line looks up the existing JavaBean, which succeeds, so the if statement is ignored.The rest of the _jspService method for Listing 6.11 contains

The out.print statement is due to the jsp:getProperty tag in the JSP.

If the JSP in Listing 6.11 had jsp:setProperty tags within the jsp:useBean tag, they would be ignored. For example, this would happen if you tried to change the author’s name with the following lines:

Remember that the body of a jsp:useBean tag is only executed when a JavaBean is created.

JavaBeans and HTML Forms

JSPs can use HTML forms to allow the user to enter information that is to be processed. In Web applications, users typically enter data such as usernames, passwords, credit-card numbers, and so on. This section shows an example that starts by passing the information that the user supplies as page parameters between two JSPs, and progresses to using a JavaBean to store the information. Consider the JSP in Listing 6.12, that displays a simple form for a user to enter details of a book.

Listing 6.12 A Form for Entering Book Details (bookEntryForm.jsp)

When the user has entered the information and clicks the submit button, the form forwards the information to the bookProcess.jsp page (see the form tag’s action attribute). The user can enter the values into the form by way of the four HTML form input fields. Even though the four form fields all have their type specified as text, it is the value of their name attributes that gives each parameter its name and, thus, distinguishes them.Whatever the user types into the field on the form is the value of the parameter. The input fields from the form are supplied to the action page as name/value pairs. The correct terminology is that form fields are passed as parameters to the next page. When the submit button is clicked, it creates a query string that is then appended to the URL that is declared in the form’s action attribute.The reason that the parameters are appended to the query string in this way is because the form’s method attribute has a value of get. If the method attribute for the form tag had a value of post instead of get, you would not see the form parameters appended to the query string. Instead, the parameters would be passed as name/value pairs in the HTTP header of a request to the second page.

For the example in Listing 6.12, if the user entered information as in the screenshot in Figure, the query string that is generated is

http://localhost:8080/chapter/beans_and_forms/bookProcess.js ?id=3&author=Joshua+Greenhough&title=Got+a+right+job+on%21&price=9.99

You can see that the URL that the form redirects the browser to is http://localhost:8080/chapter/beans_and_forms/bookProcess.jsp, and appended to this is a ? character followed by the name/value pairs for the parameters.The individual parameters are separated by the & character:


You can also see that any space characters in the parameter values are encoded using the + character, and that the exclamation mark character is encoded using its Unicode value (21 in hexadecimal).

Figure A JSP that uses an HTML form.

Figure A JSP that uses an HTML form

When the user submits values for the form fields, the values can be retrieved on a JSP by accessing the request object. See Listing 6.13, that simply displays the supplied parameters in a list.

Listing 6.13 A JSP That Displays the Form Parameters (bookProcess.jsp)

When using the get method with HTML forms, there is a limit imposed by the HTTP specification on the type of data that can be sent. As you have just seen, the get method of sending data appends form parameters to the query string. Because the query string is exactly that, a string, any data that you send must conform to the rules for URL strings. Any invalid characters must be escaped or encoded, such as the exclamation character in the previous example. There is no limit on the amount of data that can be sent using the post method.

Although there is nothing in the HTTP 1.1 specification about the limit of data that can be sent using the get method, in practice most Web servers tend to have a limit of something in the region of 1KB or 2KB.

HTML forms are a useful tool for acquiring data, but it can quickly become tedious to write code that processes the form parameters. An alternative is to use JavaBeans that store the form parameters. Form parameters are sets of unrelated name/value pairs, but they can be logically grouped by using one or more JavaBeans. This can be achieved for the current example by using the same form page as Listing 6.12, but with the action attribute changed so that it points to the JSP in Listing 6.14. You can find the modified file in the Web application from the book Web site as bookEntryForm2.jsp.

Listing 6.14 A JSP That Uses a JavaBean to Hold Parameter Values

There are two parts to Listing 6.14: a jsp:useBean tag, and the HTML code.The jsp:useBean tag and its nested jsp: setProperty tags instantiate a JavaBean and set its properties to the values of the form fields that are passed as parameters on the request object. So far, the values that have been set for a JavaBean property using the jsp:setProperty tag have been fixed values. However, the four jsp:setProperty tags in this example use a runtime expression to compute the value that is to be set. Also, note that single quotes were used to delimit the value attribute’s value.This is because the JSP expression tag itself uses double quotes in the request.getParameter()

method call.Thus, the single quotes were used to conform with the XML production rules for attribute values. Notice the code used for setting the price property:

The Double.parseDouble method was used to convert the string value for the price parameter to a double.This is so that the jsp:setProperty tag can look for a method of the JavaBean called setPrice that takes an argument of primitive type double. If this conversion is not performed, the Web container is unable to find an accessor method, and displays an error to that effect.

There is an alternative form of the jsp:setProperty tag that enables you to associate a JavaBean property with a named form parameter:

Instead of specifying a value attribute, you can instead specify a param attribute whose value is the name of the form parameter. An advantage to using this form of the tag is that it automatically performs a conversion from a string to a Java primitive datatype (boolean, byte, char, short, int, long, float, and double).The JSP in Listing 6.14 can be rewritten using this alternative form shown in Listing 6.15.

Listing 6.15 Example of Associating JavaBean Properties with Request Parameters

In fact, if you are setting each property individually, and the JavaBean property names match the parameter names, you can use a shorthand syntax: <jsp:setProperty name=”bean_name” property=”property_name” /> The downside to setting each of the properties separately becomes apparent when there are many JavaBean properties.The problem becomes even more pronounced when the form parameters on the query string do not match the property names of the JavaBean.The pages become difficult to maintain because of the added complexity.

The jsp:setProperty tag can take an alternative form of syntax.The following syntax enables you to set all properties of a JavaBean that have a matching form parameter:

<jsp:setProperty name=”bean_name” property=”*” />

It is the value of * for the value of the property attribute that is the important part.The jsp:setProperty tag inspects the form parameters, and looks for a matching set method in the JavaBean. For example, if there is a form parameter called author, a search is made for a method called setAuthor().

There are a couple of important points that apply to these last two forms of the jsp:setProperty tag (that is, associating a JavaBean property with a form parameter, or matching all JavaBean properties with form parameters).The first is that if a match cannot be found between a form parameter and a set method, the form parameter is ignored and no action is taken. If it is not possible, as part of the page and JavaBean design, to make the form parameters and JavaBean properties match, you must set the JavaBean properties explicitly as shown in Listing 6.15. The second important point to note pertains to JavaBean properties that are not of type java.lang.String. Again, consider the conversion that had to be made when setting the price property in Listing 6.14, from a string to a double. An automatic conversion is made from a string to a Java primitive type when you map JavaBean properties to either all, or named, form parameters.The implementation of the conversions is in terms of the wrapper classes that are provided as part of the java.lang package. Because the example for this section of the book has form parameters with the same names as the JavaBean properties, then the JSP in Listing 6.15 can be rewritten as shown in Listing 6.16.

Listing 6.16 A JSP That Associates All Form Parameters with JavaBean Properties (bookProcessBeanAllParams.jsp)

Finally, a word about the limitations of the jsp:getProperty and jsp:setProperty tags. It is possible from a scriptlet or expression tag to access a JavaBean property directly, either by name or by accessor method (assuming of course that the property or accessor method is not inaccessible, for example, if it is declared as private). However, the jsp:getProperty and jsp:setProperty tags only enable you to access JavaBean properties that follow the naming conventions set out in the JavaBeans specification.That is, for a property called foo, the accessor methods must be of the form isFoo()/setFoo() for boolean types, and getFoo()/setFoo() for other data types.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JSP Topics