introduction to javabeans
DESCRIPTION
Basic information on how to code JavaBeansTRANSCRIPT
Introduction to JavaBeans
Objectives:
• Understand the benefits of JavaBeans
• Learn how to create JavaBeans
• Utilize JavaBean classes
• Demonstrate how to access JavaBean properties
• Explicitly setting JavaBean properties from request parameters
Concepts
As we have discussed on our previous lesson, (Using Regular Classes in JSP), we understood
the benefits of using separate Java classes instead of embedding large amounts of code directly in JSP
pages. But what do JavaBeans provide that other classes do not? After all , JavaBeans are regular Java
classes that follow some conventions defined by the JavaBeans specification; JavaBeans extend no
particular class, are in no particular package and use no particular interface. True, but with JavaBeans in
general, visual manipulation tools and other programs can automatically discover information about
classes that follow this format and can create and manipulate the classes without user having to
explicitly write any code.
The Advantages of JavaBeans in JSP in Particular are:
1. No Java syntax. By using JavaBeans, page authors can manipulate Java objects using only XML-
compatible syntax. This promotes a stronger separation between the content and the
presentation and is especially useful in large development teams that have separate Web and
Java Developers.
2. Simpler object sharing. When you use the JSP JavaBean constructs, you can much more easily
share objects among multiple pages or between requests than if you use the equivalent Java
code.
3. Convenient correspondence between request parameters and object properties. The JSP
JavaBean constructs greatly simplify the process of reading request parameters, converting from
strings and putting the results inside objects.
What are JavaBeans - How To Code a JavaBean
1. A JavaBean must contain a constructor that does not accept any arguments.
2. A JavaBean cannot declare any public instance variables. However, it is also possible to declare
instance variables as protected.
3. A JavaBean must contain get and set methods for all properties that need to be accessed by
JSPs.
o The setter method is just a method that starts with “set” followed by the name of the
property. Take note that the first character of the property is upper-cased.
o The getter method is just a method that starts with “get” followed by the name of the
property. Take note that the first character of the property is upper-cased.
o To provide access to a Boolean value, you code is and set methods instead of get and set
methods.
o Example, you can code methods isEmailUpdated and setEmailUpdated to provide access
to a Boolean property named emailUpdated.
4. A JavaBean implements the Serializable interface.
o The Serializable interface is a tagging interface in the java.io package that indicates that
a class contains get,set and is methods that another class can read and write an object's
instance variables to and from a persistent data source
o Example: your JavaBean is on a server in New York helping the rest of an application in
Los Angeles. The Java application server hosting your JavaBean receives a message that
the server is going down for maintenance, so it contacts another server elsewhere and
arranges for the other server to take over. Not wanting to crash out an end user using
your JavaBean, the Java application server has your JavaBean save its state, using
serialization and it moves the JavaBean location and data to the new server, where the
saved JavaBean data is loaded again and the user continues using the application
without noticing a thing.
JavaBean Tags
The main benefit that you get from coding your classes so they qualify as JavaBeans is that you can then
use JSP tags for working with the beans.
The useBean tag
The <jsp:useBean> element locates or instantiates a JavaBean component. It first attempts to locate an
instance of the Bean. If the JavaBean does not exists, <jsp:useBean> instantiates it from a class or
serialized template.
To locate or instantiate the Bean, <jsp:useBean> takes the following steps, in this 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
byjava.beans.Beans.instantiate.
5. If <jsp:useBean> has instantiated (rather than located) the Bean, and if it has body tags or
elements (between<jsp:useBean> and </jsp:useBean>), executes the body tags.
Syntax
<jsp:useBean id=”object-name”
scope=”page | request | session | application”
type=”package.class”
class=”package.class”
beanName=”fully-qualified-bean-name”
/>
Example:
<jsp:useBean id="checking" scope="session" class="bank.Checking" >
Attributes and Usage
id=”object-name”
• A variable that identifies the Bean in the scope you specify. You can use the variable name in
expressions or scriptlets in the JSP file.
scope=”page | request | session | application”
• The scope in which the JavaBean exists and the variable named in id is available. The default
value is page.
o page - The bean is stored in the implicit pageContext object for the JSP and is only
available to the current page.
o request - The bean is stored in the HttpServletRequest object and is available to all JSPs
that have access tot eh current request object.
Page and request scope JavaBeans are sometimes referred to as form beans because they most often
process the results of a form. Form beans need to exist just long enough to process user input, usually
being instantiated on the page that recieves the HTTP POST or GET request with parameters.
o session – The bean is stored in the HttpSession object and is available to all JSPs that
have access to this object. Session-scoped JavaBeans are great for activities that take
place over several pages and time: filling a shopping cart, incrementally filling out
information and receiving feedback.
o aplication – The bean is stored in the ServletContext object. Application scope is most
often used by server components such as JDBC Connection pools, application monitors,
user counters and other classes that participate indirectly with a user's activities.
class=”package.class”
o Instantiate a bean from a class, using the new keyword and the class constructor. The
class must not be abstract and have a public, no-argument constructor. The package and
class name is case-sensitive.
type=”package.class”
o If the bean already exists in the scope, gives the bean a data type other than the class
from which it was instantiated.
The setProperty tag
Syntax
<jsp:setProperty
name=”beanInstanceName”
property=”*” |
property=”propertyName” [param=”parameterName”] |
property="propertyName" value="{string| <%=expression%>}"
/>
The <jsp:setProperty> element sets the value of one or more properties in a Bean, using the Bean's
setter methods. You must declare the Bean with <jsp:useBean> before you set a property value with
<jsp:setProperty>
You can use <jsp:setProperty> to set property values in several ways.
1. By passing all the values the user enters (stored as parameters in the request object) to
matching properties in the Bean
2. By passing a specific value the user enters to a specific property in the Bean
3. By setting a Bean property to a value you specify as either a String or an expression that is
evaluated at runtime.
Attributes
name=”beanInstanceName”
• The name of the JavaBean that has already been created or located with a <jspLuseBean> tag.
The value of name must match the value of id in <jsp:useBean>. The <jsp:useBean> tag must
appear before <jsp:setProperty> in the JSP page.
property=”*”
• Stores all of the values of request parameters in bean properties. The names of the JavaBean
properties must match the names of the request parameters. A JavaBean property is usually
defined by a variable declaration with matching getter and setter methods. If the order in which
the properties are set is important to how your JavaBean works, use the syntax form
property=”propertyName” [ param=”parameterName” ]
• Sets one JavaBean property to the value of one request parameter. In the syntax, property
specifies the name of the JavaBean property and param specifies the name of the request
parameter by which data is being sent from the client to the server.
The getProperty tag
Syntax:
<jsp:getProperty name=”beanInstanceName” property=”propertyName” />
Attributes
name=”beanInstanceName”
• The name of an object (usually an instance of a bean) declared in jsp:useBean tag.
property=”propertyName”
• The name of the JavaBean property whose value you want to display. The property is declared
as a variable in a bean and must have a corresponding getter method.
The <jsp:getProperty> tag gets a JavaBean property value using the property’s getter methods and
inserts the value into the response. You must create or locate a bean with <jsp:useBean> before use
<jsp:getProperty>.
1 package coreservlets;
2
3 /** A simple bean that has a single String property
called message */
4
5 public class StringBean {
6
7 private String message = "Hello JSP Students!
Happy Coding!";
8
9 public String getMessage(){
10 return message;
11 }
12
13 public void setMessage(String m){
14 message = m;
15 }
16
17 }
1
1 <!-- StringBean.jsp -->
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <style type="text/css">
6 i { color:#D00;
7 font-weight:bold; }
8
9 </style>
10 <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
11 <title>JavaBean Simple Example</title>
12 </head>
13
14 <body>
15 <table border="5" align="center">
16 <tr> <th>A Simple JavaBean Example</th></tr>
17 </table>
18 <jsp:useBean id="sb" class=
"coreservlets.StringBean" />
19 <ol>
20 <li> Initial value (from jsp:getProperty): <i><
jsp:getProperty name="sb" property="message"
/></i></li>
21 <li>Initial value (from JSP expression): <i><%=
sb.getMessage() %></i></li>
22 <li><jsp:setProperty name="sb" property="message"
value="The Best Elective Class I Ever Had" />
Value after setting property with jsp:setProperty:
<i><jsp:getProperty name="sb" property="message"
/></i></li>
23 <li><% sb.setMessage("Definitely My Favorite"); %>
Value after setting property with scriptlet:
<i><%= sb.getMessage() %></i></li>
24 </ol>
25
26 </body>
27 </html>
1
1 package coreservlets;
2 /** Simple bean to illustrate the various forms of
jsp:setProperty */
3
4 public class SaleEntry {
5 private String itemID = "unknown";
6 private double discountCode = 1.0;
7 private int numItems = 0;
8
9 public String getItemID(){
10 return itemID;
11 }
12 public void setItemID(String id){
13 itemID = "unknown";
14 if(id != null){
15 itemID = id;
16 }
17 }
18 public double getDiscountCode(){
19 return discountCode;
20 }
21 public void setDiscountCode(double code){
22 discountCode = code;
23 }
24 public int getNumItems(){
25 return numItems;
26 }
27 public void setNumItems(int items){
28 numItems = items;
29 }
30 public double getItemCost(){
31 double cost = -9999;
32 if(itemID.equals("emac321")){
33 cost = 12.99 * getDiscountCode();
34 }
35 return roundToCentavos(cost);
36 }
37 private double roundToCentavos(double c){
38 return (Math.floor(c*100)/100.0);
39 }
40 public double getTotalCost(){
41 return (getItemCost() * getNumItems());
1
42 }
43 /** In actuality, this is done through a
database lookup.
44 We will have a similar example when we get
to the JDBC
45 part of our lesson
46 */
47
48 } //end class
2
1 <!-- SaleEntry.jsp -->
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
6 <title>JavaBean Example - Sale Entry</title>
7 </head>
8
9 <body>
10 <center><table border="5"><tr><th>Using
jsp:setProperty</th></tr></table>
11 <jsp:useBean id="entry" class=
"coreservlets.SaleEntry" />
12 <jsp:setProperty name="entry" property="itemID"
value='<%= request.getParameter("itemID") %>' />
13 <%
14 int numItemsOrdered = 1;
15 try {
16 numItemsOrdered = Integer.parseInt(
request.getParameter("numItems") );
17 }
18 catch(NumberFormatException nfe){}
19 %>
20 <jsp:setProperty name="entry" property="numItems"
value='<%= numItemsOrdered %>' />
21
22 <%
23 double discountCode = 1.0;
24 try {
25 String discountString = request.
getParameter("discountCode");
26 discountCode = Double.parseDouble(
discountString);
27 }
28 catch(NumberFormatException nfe){ }
29 %>
30 <jsp:setProperty name="entry" property=
"discountCode" value="<%= discountCode %>" />
1
31 <br />
32 <table border="1">
33 <tr>
34 <th>Item ID</th>
35 <th>Unit Price</th>
36 <th>Number Ordered</th>
37 <th>Total Price</th>
38 </tr>
39 <tr align="right">
40 <td><jsp:getProperty name="entry" property=
"itemID" /> </td>
41 <td>$<jsp:getProperty name="entry" property=
"itemCost" /></td>
42 <td><jsp:getProperty name="entry" property=
"numItems" /></td>
43 <td>$<jsp:getProperty name="entry" property=
"totalCost" /></td>
44 </tr>
45 </table>
46 </center>
47
48 </body>
49 </html>
2
1 <!-- SaleEntryForm.jsp -->
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
6 <title>JavaBean Example - Sale Entry Form</title>
7 </head>
8
9 <body>
10 <center>
11 <table border="5"><tr><th>Invoking SaleEntr
y.jsp</th></tr></table><p>
12 <form action="SaleEntry.jsp" method="post">
13 <table border="1" style=
"border-collapse:collapse">
14 <tr>
15 <td>Item ID: </td><td><input type=
"text" name="itemID" /></td>
16 </tr>
17 <tr>
18 <td>Number of Items</td><td><input
type="text" name="numItems" /></td>
19 </tr>
20 <tr>
21 <td>Discount Code</td><td><input
type="text" name="discountCode" /><
/td>
22 </tr>
23 <tr>
24 <td colspan="2"><input type=
"submit" value="Show Price" /></td>
25 </tr>
26 </table>
27 </form>
28 </p>
29 </center>
30 </body>
31 </html>
1
StringBean.jsp
SaleEntryForm.jsp
SaleEntry.jsp
Associating Individual Properties with Input Parameters
Setting the itemID property is easy since its value is a String. Setting the numItems and
discountCode properties is a bit more problematic since their values must be numbers whereas
getParameter returns a String.
Fortunately, JSP has a nice solution to this problem. It lets you associate a property with a
request parameter and automatically perform type conversion from strings to numbers, characters and
Boolean values. Instead of using the value attribute, you use the param to name an input parameter.
The value of the named request parameter is automatically used as the value of the bean property and
type conversions from String to primitive types (byte, int, Boolean, double, etc) and wrapper classes
(Byte, Integer, Double, etc) are automatically performed. If the specified parameter is missing from the
request, no action is taken (the system does not pass null to the associated property). For example,
setting the numItems property can be simplified to:
<jsp:setProperty name=”entry” property=”numItems” param=”numItems” />
Associating All Properties with Request Parameters
Associating a property with a request parameter saves you the bother of performing
conversions for many of the simple built-in types. JSP lets you take the process one step further by
associating all properties with identical named request parameters. All you have to do is to supply “*”
for the property parameter. So, for example, all three of the jsp:setProperty statements on the previous
example (SaleEntry.jsp) can be replaced by the following simple line:
<jsp:setProperty name=”entry” property=”*” />
Although this approach is simple, there are warnings that one should consider:
• No action is taken when an input parameter is missing. In particular, the system does not
supply null as the property value. You usually design beans to have identifiable default values
that let you determine if a property has been modified.
• Automatic type conversion does not guard against illegal values as effectively as does manual
type conversion. In fact, despite the convenience of automatic type conversion, some
developers eschew the automatic type conversion, define all of their settable bean properties to
be of type String and use explicit try/catch blocks to handle malformed data.
• Bean property names and request parameters are case sensitive. The property name and
request parameter name must match exactly.