Introduction To JavaBeans
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 XMLcompatible 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.
o 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. 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. To provide access to a Boolean value, you code is and set methods instead of get and set methods. Example, you can code methods isEmailUpdated and setEmailUpdated to provide access to a Boolean property named emailUpdated.
o 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 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.
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. 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 propertys getter methods and inserts the value into the response. You must create or locate a bean with <jsp:useBean> before use <jsp:getProperty>.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package coreservlets; /** A simple bean that has a single String property called message */ public class StringBean { private String message = "Hello JSP Students! Happy Coding!"; public String getMessage(){ return message; } public void setMessage(String m){ message = m; } }
1 2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<!-- StringBean.jsp --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> i { color:#D00; font-weight:bold; } </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaBean Simple Example</title> </head> <body> <table border="5" align="center"> <tr> <th>A Simple JavaBean Example</th></tr> </table> <jsp:useBean id="sb" class= "coreservlets.StringBean" /> <ol> <li> Initial value (from jsp:getProperty): <i>< jsp:getProperty name="sb" property="message" /></i></li> <li>Initial value (from JSP expression): <i><%= sb.getMessage() %></i></li> <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> <li><% sb.setMessage("Definitely My Favorite"); %> Value after setting property with scriptlet: <i><%= sb.getMessage() %></i></li> </ol> </body> </html>
21 22
23
24 25 26 27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
package coreservlets; /** Simple bean to illustrate the various forms of jsp:setProperty */ public class SaleEntry { private String itemID = "unknown"; private double discountCode = 1.0; private int numItems = 0; public String getItemID(){ return itemID; } public void setItemID(String id){ itemID = "unknown"; if(id != null){ itemID = id; } } public double getDiscountCode(){ return discountCode; } public void setDiscountCode(double code){ discountCode = code; } public int getNumItems(){ return numItems; } public void setNumItems(int items){ numItems = items; } public double getItemCost(){ double cost = -9999; if(itemID.equals("emac321")){ cost = 12.99 * getDiscountCode(); } return roundToCentavos(cost); } private double roundToCentavos(double c){ return (Math.floor(c*100)/100.0); } public double getTotalCost(){ return (getItemCost() * getNumItems()); 1
42 43 44 45 46 47 48
} /** In actuality, this is done through a database lookup. We will have a similar example when we get to the JDBC part of our lesson */ } //end class
1 2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<!-- SaleEntry.jsp --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaBean Example - Sale Entry</title> </head> <body> <center><table border="5"><tr><th>Using jsp:setProperty</th></tr></table> <jsp:useBean id="entry" class= "coreservlets.SaleEntry" /> <jsp:setProperty name="entry" property="itemID" value='<%= request.getParameter("itemID") %>' /> <% int numItemsOrdered = 1; try { numItemsOrdered = Integer.parseInt( request.getParameter("numItems") ); } catch(NumberFormatException nfe){} %> <jsp:setProperty name="entry" property="numItems" value='<%= numItemsOrdered %>' /> <% double discountCode = 1.0; try { String discountString = request. getParameter("discountCode"); discountCode = Double.parseDouble( discountString); } catch(NumberFormatException nfe){ } %> <jsp:setProperty name="entry" property= "discountCode" value="<%= discountCode %>" /> 1
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
<br /> <table border="1"> <tr> <th>Item ID</th> <th>Unit Price</th> <th>Number Ordered</th> <th>Total Price</th> </tr> <tr align="right"> <td><jsp:getProperty name="entry" property= "itemID" /> </td> <td>$<jsp:getProperty name="entry" property= "itemCost" /></td> <td><jsp:getProperty name="entry" property= "numItems" /></td> <td>$<jsp:getProperty name="entry" property= "totalCost" /></td> </tr> </table> </center> </body> </html>
1 2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!-- SaleEntryForm.jsp --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaBean Example - Sale Entry Form</title> </head> <body> <center> <table border="5"><tr><th>Invoking SaleEntr y.jsp</th></tr></table><p> <form action="SaleEntry.jsp" method="post"> <table border="1" style= "border-collapse:collapse"> <tr> <td>Item ID: </td><td><input type= "text" name="itemID" /></td> </tr> <tr> <td>Number of Items</td><td><input type="text" name="numItems" /></td> </tr> <tr> <td>Discount Code</td><td><input type="text" name="discountCode" />< /td> </tr> <tr> <td colspan="2"><input type= "submit" value="Show Price" /></td> </tr> </table> </form> </p> </center> </body> </html> 1
22 23 24 25 26 27 28 29 30 31
StringBean.jsp
SaleEntryForm.jsp
SaleEntry.jsp