JSP Tutorials - Herong's Tutorial Examples - v5.11, by Herong Yang
Using Java Objects as JavaBeans
This section provides a tutorial example on how to use a regular Java object as JavaBean using the 'setProperty' action elements. This requires the Java object to be added to 'pageContext' attribute collection.
Now we know that a JavaBean is just a normal Java object with some specially named methods, and stored in pageContext's attribute collection. We can use the useBean to create a JavaBean and use it any way we wanted.
The next question is: can we create any object and put it into pageContext's attribute collection, and use setProperty elements? The answer is yes. Here is my sample JSP page to show you this:
<?xml version="1.0"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"> <!-- ObjectAsBean.jspx - Copyright (c) 2006 HerongYang.com. All Rights Reserved. --> <jsp:directive.page contentType="text/html"/> <html><body> <jsp:scriptlet><![CDATA[ herong.DemoBean b = new herong.DemoBean(); pageContext.setAttribute("b", b, PageContext.PAGE_SCOPE); ]]></jsp:scriptlet> <jsp:setProperty name="b" property="author" value="Unknown"/> Line 21: author = <jsp:expression>b.getAuthor()</jsp:expression><br/> Line 22: total = <jsp:expression>b.getTotal()</jsp:expression><br/> <jsp:scriptlet><![CDATA[b.setSize(15);]]></jsp:scriptlet> Line 23: size = <jsp:expression>b.getSize()</jsp:expression><br/> Line 24: size = <jsp:scriptlet>out.println(b.getSize());</jsp:scriptlet><br/> <jsp:scriptlet><![CDATA[ java.util.Date d = new java.util.Date(); pageContext.setAttribute("d", d, PageContext.PAGE_SCOPE); ]]></jsp:scriptlet> <jsp:setProperty name="d" property="time" value="1000000000000"/> Line 25: time = <jsp:expression>d.getTime()</jsp:expression><br/> </body></html> </jsp:root>
Open this JSP page with a Web browser, you will get:
Line 21: author = Unknown Line 22: total = 1 Line 23: size = int: 15 Line 24: size = int: 15 Line 25: time = 1000000000000
Note that:
Notice that, I am not using "getProperty" action elements in this example. Why? Because it does work not in Tomcat. See next tutorial for more details.
Table of Contents
JSP (JavaServer Pages) Overview
Tomcat Installation on Windows Systems
Syntax of JSP Pages and JSP Documents
►JavaBean Objects and "useBean" Action Elements
"jsp:useBean" Requires Fully Qualified Class Name
Servlet Class Converted from UseBean.jspx
Setting and Getting JavaBean's Properties
Using JavaBean Objects in Scripting Elements
►Using Java Objects as JavaBeans
getProperty() Error on Tomcat 7
Refreshing Loaded JavaBean Classes
Importing Unnamed Package Class Error
Using JavaBean without Import Element Error
Creating JavaBean Classes in Named Packages
"NoClassDefFoundError" Exception
Managing HTTP Response Header Lines
Non-ASCII Characters Support in JSP Pages
Overview of JSTL (JSP Standard Tag Libraries)
Multiple Tags Working Together
Using Tomcat on CentOS Systems
Connecting to SQL Server from Servlet