JSP and JSTL Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 3.09, 2006

Using JavaBean Classes

Part:   1  2  3  4  5 

JSP/JSTL Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Using Cookies

Using JavaBean Classes

HTTP Response Header Lines

Non ASCII Characters

JSTL and Expression Language

File Upload

Execution Context

JSP Elements

JSP Standard Tag Libraries (JSTL)

JSP Custom Tag

... Table of Contents

(Continued from previous part...)

Note that:

  • Property names are case sensitive. Property name "Author" can not be mapped to "getAuthor" method.
  • Two set methods without any one taking String as input parameter type is giving me problem to set "total".
  • Two set methods with one taking String as input parameter type is ok. Output line 5 is the prove.

Using JavaBeans as Objects in Scripting Elements

As I mentioned in the previous section, JavaBean is just a normal Java object with some special method. Once a JavaBean is created, we should be able to use it as Java object in any scripting elements.

Here is a sample page to show you how to use a JavaBean as a Java object. It is using the same JavaBean class, herong.DemoBean, as the previous section.

<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- BeanAsObject.jsp
     Copyright (c) 2003 by Dr. Herong Yang
-->
<html><body>
<jsp:useBean id="b" class="herong.DemoBean"/>
<jsp:setProperty name="b" property="author" value="Someone"/>
Line 11: author = 
<jsp:expression>b.getAuthor()</jsp:expression><br/>

<jsp:scriptlet><![CDATA[b.setTotal(10);]]></jsp:scriptlet>
Line 12: total = 
<jsp:getProperty name="b" property="total"/><br/>

<jsp:scriptlet><![CDATA[b.setSize(15);]]></jsp:scriptlet>
Line 13: size = 
<jsp:getProperty name="b" property="size"/><br/>
Line 14: size = 
<jsp:scriptlet><![CDATA[out.println(b.getSize());]]></jsp:scriptlet>
<br/>

<jsp:scriptlet><![CDATA[
   Object o = pageContext.findAttribute("b");
   String s = ((herong.DemoBean)o).getSize();
   out.println("Line 15: size = "+s);
]]></jsp:scriptlet><br/>
</body></html>
</jsp:root>

Open this JSP page with IE, you will get:

Line 11: author = Someone
Line 12: total = int: 10
Line 13: size = int: 15
Line 14: size = int: 15 
Line 15: size = int: 15 

Note that:

  • Line 11 tells us that we can use an expression element to get the property value.
  • Line 12 tells us that if we use scriptlet element, we can call a specific version of setTotal method. Remember setProperty failed on "total" in the previous example.
  • Line 15 tells us that we also retrieve the object back from pageContext, because useBean element store the JavaBean object in pageContext.

(Continued on next part...)

Part:   1  2  3  4  5 

Dr. Herong Yang, updated in 2006
JSP and JSTL Tutorials - Herong's Tutorial Notes - Using JavaBean Classes