0% found this document useful (0 votes)
9 views28 pages

13 JavaBeans

The document provides an overview of using JavaBeans in JSP, detailing the benefits, creation, and management of beans. It explains key JSP tags like jsp:useBean, jsp:setProperty, and jsp:getProperty for instantiating and manipulating beans, as well as the importance of using accessors instead of public fields. Additionally, it discusses the scope of beans and how to share them across multiple servlets and JSP pages.

Uploaded by

Tseng Sean
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

13 JavaBeans

The document provides an overview of using JavaBeans in JSP, detailing the benefits, creation, and management of beans. It explains key JSP tags like jsp:useBean, jsp:setProperty, and jsp:getProperty for instantiating and manipulating beans, as well as the importance of using accessors instead of public fields. Additionally, it discusses the scope of beans and how to share them across multiple servlets and JSP pages.

Uploaded by

Tseng Sean
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

© 2008 Marty Hall

Using JavaBeans
Components in JSP
Documents
Customized Java EE Training: [Link]
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
2 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2008 Marty Hall

For live Java training, please see training courses at


[Link] Servlets, JSP, Struts,
JSF, Ajax, GWT, Java 5, Java 6, & customized
combinations of topics. Spring/Hibernate coming soon.

Taught by the author of Core Servlets and JSP, More


Servlets and JSP, and this tutorial. Available at
public venues, or customized versions can be held
Customized Java EE Training: [Link]
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
3 on-siteauthor
Developed and taught by well-known at and
your organization.
developer. At public venues or onsite at your location.
Agenda
• Understanding the benefits of beans
• Creating beans
• Installing bean classes on your server
• Accessing bean properties
• Explicitly setting bean properties
• Automatically setting bean properties from
request parameters
• Sharing beans among multiple servlets and
JSP pages

4 Java EE training: [Link]

Uses of JSP Constructs

• Scripting elements calling servlet


Simple code directly
Application
• Scripting elements calling servlet
code indirectly (by means of utility
classes)
• Beans
• Servlet/JSP combo (MVC)
• MVC with JSP expression language
Complex • Custom tags
Application • MVC with beans, custom tags, and
a framework like Struts or JSF
5 Java EE training: [Link]
Background: What Are Beans?
• Java classes that follow certain conventions
– Must have a zero-argument (empty) constructor
• You can satisfy this requirement either by explicitly
defining such a constructor or by omitting all constructors
– Should have no public instance variables (fields)
• I hope you already follow this practice and use accessor
methods instead of allowing direct access to fields
– Persistent values should be accessed through methods
called getXxx and setXxx
• If class has method getTitle that returns a String, class is
said to have a String property named title
• Boolean properties use isXxx instead of getXxx
– For more on beans, see
[Link]
6 Java EE training: [Link]

Why You Should Use


Accessors, Not Public Fields
• To be a bean, you cannot have public fields
• So, you should replace
public double speed;
• with
private double speed;

public double getSpeed() {


return(speed);
}
public void setSpeed(double newSpeed) {
speed = newSpeed;
}
• You should do this in all your Java code
anyhow. Why?
7 Java EE training: [Link]
Why You Should Use
Accessors, Not Public Fields
• 1) You can put constraints on values
public void setSpeed(double newSpeed) {
if (newSpeed < 0) {
sendErrorMessage(...);
newSpeed = [Link](newSpeed);
}
speed = newSpeed;
}

– If users of your class accessed the fields directly, then


they would each be responsible for checking constraints.

8 Java EE training: [Link]

Why You Should Use


Accessors, Not Public Fields
• 2) You can change your internal
representation without changing interface
// Now using metric units (kph, not mph)

public void setSpeed(double newSpeed) {


setSpeedInKPH = convert(newSpeed);
}

public void setSpeedInKPH(double newSpeed) {


speedInKPH = newSpeed;
}

9 Java EE training: [Link]


Why You Should Use
Accessors, Not Public Fields
• 3) You can perform arbitrary side effects
public double setSpeed(double newSpeed) {
speed = newSpeed;
updateSpeedometerDisplay();
}

– If users of your class accessed the fields directly, then


they would each be responsible for executing side effects.
Too much work and runs huge risk of having display
inconsistent from actual values.

10 Java EE training: [Link]

Using Beans: Basic Tasks


• jsp:useBean
– In the simplest case, this element builds a new bean.
It is normally used as follows:
<jsp:useBean id="beanName"
class="[Link]" />
• jsp:setProperty
– This element modifies a bean property (i.e., calls a method of the
form setXxx). It is normally used as follows:
<jsp:setProperty name="beanName"
property="propertyName"
value="propertyValue" />
• jsp:getProperty
– This element reads and outputs the value of a bean property.
It is used as follows:
<jsp:getProperty name="beanName"
property="propertyName" />
11 Java EE training: [Link]
General Approach with Standalone
Pages and jsp:useBean Tags
• User submits form that refers to a JSP page
– <FORM ACTION="[Link]">
• JSP page instantiates a bean
– <jsp:useBean id="myBean" class="…"/>
• You pass some request data to the bean
– <jsp:setProperty name="myBean"
property="customerID"
value="…"/>
• You output some value(s) derived from the
request data
– <jsp:getProperty name="myBean"
property="bankAccountBalance"/>
12 Java EE training: [Link]

Building Beans: jsp:useBean


• Format
– <jsp:useBean id="name" class="[Link]" />
• Purpose
– Allow instantiation of Java classes without explicit Java
programming (XML-compatible syntax)
• Notes
– Simple interpretation:
<jsp:useBean id="book1" class="[Link]" />
can be thought of as equivalent to the scriptlet
<% [Link] book1 = new [Link](); %>
– But jsp:useBean has two additional advantages:
• It is easier to derive object values from request parameters
• It is easier to share objects among pages or servlets
13 Java EE training: [Link]
Setting Simple Bean Properties:
jsp:setProperty
• Format
– <jsp:setProperty name="name"
property="property"
value="value" />
• Purpose
– Allow setting of bean properties (i.e., calls to setXxx
methods) without explicit Java programming
• Notes
– <jsp:setProperty name="book1"
property="title"
value="Core Servlets and JavaServer Pages" />
is equivalent to the following scriptlet
<% [Link]("Core Servlets and JavaServer Pages"); %>
14 Java EE training: [Link]

Accessing Bean Properties:


jsp:getProperty
• Format
– <jsp:getProperty name="name" property="property" />
• Purpose
– Allow access to bean properties (i.e., calls to getXxx
methods) without explicit Java programming
• Notes
– <jsp:getProperty name="book1" property="title" />
is equivalent to the following JSP expression
<%= [Link]() %>

15 Java EE training: [Link]


Example: StringBean
package coreservlets;
public class StringBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
[Link] = message;
}
}
• Beans installed in normal Java directory
– MyEclipse: src/folderMatchingPackage
– Deployment: WEB-INF/classes/folderMatchingPackage
• Beans must always be in packages!
16 Java EE training: [Link]

JSP Page That Uses StringBean


(Code)
<jsp:useBean id="stringBean"
class="[Link]" />
<OL>
<LI>Initial value (from jsp:getProperty):
<I><jsp:getProperty name="stringBean"
property="message" /></I>
<LI>Initial value (from JSP expression):
<I><%= [Link]() %></I>
<LI><jsp:setProperty name="stringBean"
property="message"
value="Best string bean: Fortex" />
Value after setting property with jsp:setProperty:
<I><jsp:getProperty name="stringBean"
property="message" /></I>
<LI><% [Link]
("My favorite: Kentucky Wonder"); %>
Value after setting property with scriptlet:
<I><%= [Link]() %></I>
</OL>
17 Java EE training: [Link]
JSP Page That Uses StringBean
(Result)

18 Java EE training: [Link]

Setting Bean Properties Case 1:


Explicit Conversion & Assignment
<!DOCTYPE ...>
...
<jsp:useBean id="entry"
class="[Link]" />

<%-- setItemID expects a String --%>

<jsp:setProperty
name="entry"
property="itemID"
value='<%= [Link]("itemID") %>' />

19 Java EE training: [Link]


Setting Bean Properties Case 1:
Explicit Conversion & Assignment
<%
int numItemsOrdered = 1;
try {
numItemsOrdered =
[Link]([Link]("numItems"));
} catch(NumberFormatException nfe) {}
%>

<%-- setNumItems expects an int --%>

<jsp:setProperty
name="entry"
property="numItems"
value="<%= numItemsOrdered %>" />

20 Java EE training: [Link]

Setting Bean Properties Case 1:


Explicit Conversion & Assignment
<%
double discountCode = 1.0;
try {
String discountString =
[Link]("discountCode");
discountCode =
[Link](discountString);
} catch(NumberFormatException nfe) {}
%>

<%-- setDiscountCode expects a double --%>

<jsp:setProperty
name="entry"
property="discountCode"
value="<%= discountCode %>" />
21 Java EE training: [Link]
Setting Bean Properties Case 1:
Explicit Conversion & Assignment

22 Java EE training: [Link]

Case 2: Associating Individual


Properties with Input Parameters
• Use the param attribute of jsp:setProperty
to indicate that
– Value should come from specified request parameter
– Simple automatic type conversion should be performed
for properties that expect values of standard types
• boolean, Boolean, byte, Byte, char, Character, double,
Double, int, Integer, float, Float, long, or Long.

23 Java EE training: [Link]


Case 2: Associating Individual
Properties with Input Parameters
<jsp:useBean id="entry"
class="[Link]" />
<jsp:setProperty
name="entry"
property="itemID"
param="itemID" />
<jsp:setProperty
name="entry"
property="numItems"
param="numItems" />
<jsp:setProperty
name="entry"
property="discountCode"
param="discountCode" />
24 Java EE training: [Link]

Case 3: Associating All


Properties with Input Parameters
• Use "*" for the value of the property
attribute of jsp:setProperty to indicate that
– Value should come from request parameter whose name
matches property name
– Simple automatic type conversion should be performed

25 Java EE training: [Link]


Case 3: Associating All
Properties with Input Parameters
<jsp:useBean id="entry"
class="[Link]" />
<jsp:setProperty name="entry" property="*" />

• This is extremely convenient for making


"form beans" -- objects whose properties
are filled in from a form submission.
– You can even divide the process up across multiple
forms, where each submission fills in part of the object.

26 Java EE training: [Link]

Sharing Beans
• You can use the scope attribute to specify
additional places where bean is stored
– Still also bound to local variable in _jspService
– <jsp:useBean id="…" class="…"
scope="…" />
• Lets multiple servlets or JSP pages
share data
• Also permits conditional bean creation
– Creates new object only if it can't find existing one

27 Java EE training: [Link]


Sharing Beans: Example
• [Link]
<jsp:useBean id="foo" class="…" scope="application"/>
<jsp:setProperty name="foo" property="message"
value="Hello"/>
<jsp:getProperty name="foo" property="message">
• [Link]
<jsp:useBean id="foo" class="…" scope="application"/>
<jsp:getProperty name="foo" property="message">
• Possible scenario 1
– Joe goes to page 2 (output is "Default Message")
– Jane goes to page 1 (output is "Hello")
• Possible scenario 2
– Joe goes to page 1 (output is "Hello")
– Jane goes to page 2 (output is "Hello")
28 Java EE training: [Link]

Values of the scope Attribute


• page (<jsp:useBean … scope="page"/> or
<jsp:useBean…>)
– Default value. Bean object should be placed in the
PageContext object for the duration of the current
request. Lets methods in same servlet access bean
• application
(<jsp:useBean … scope="application"/>)
– Bean will be stored in ServletContext (available through
the application variable or by call to getServletContext()).
ServletContext is shared by all servlets in the same Web
application (or all servlets on server if no explicit Web
applications are defined).

29 Java EE training: [Link]


Values of the scope Attribute
• session
(<jsp:useBean … scope="session"/>)
– Bean will be stored in the HttpSession object associated
with the current request, where it can be accessed from
regular servlet code with getAttribute and setAttribute, as
with normal session objects.
• request
(<jsp:useBean … scope="request"/>)
– Bean object should be placed in the ServletRequest object
for the duration of the current request, where it is
available by means of getAttribute

30 Java EE training: [Link]

Sharing Beans in Four Different


Ways
• Using unshared (page-scoped) beans.
• Sharing request-scoped beans.
• Sharing session-scoped beans.
• Sharing application-scoped (i.e.,
ServletContext-scoped) beans.

• Important:
– Use different names (i.e., id in jsp:useBean) for different
beans
31 • Don't store beans in different Java
places with same id
EE training: [Link]
Sharing Beans Four Ways:
Bean Code
package coreservlets;

public class BakedBean {


private String level = "half-baked";
private String goesWith = "hot dogs";

public String getLevel() {


return(level);
}
public void setLevel(String newLevel) {
level = newLevel;
}
public String getGoesWith() {
return(goesWith);
}
public void setGoesWith(String dish) {
goesWith = dish;
}
32
} Java EE training: [Link]

Sharing Beans Example 1:


Page-Scoped (Unshared)
• Create the bean
– Use jsp:useBean with scope="page" (or no scope at all,
since page is the default).
• Modify the bean
– Use jsp:setProperty with property="*".
– Then, supply request parameters that match the bean
property names.
• Access the bean
– Use jsp:getProperty.

33 Java EE training: [Link]


Sharing Beans Example 1:
Page-Scoped (Unshared)

<BODY>
<H1>Baked Bean Values: page-based Sharing</H1>
<jsp:useBean id="pageBean"
class="[Link]" />
<jsp:setProperty name="pageBean" property="*" />
<H2>Bean level:
<jsp:getProperty name="pageBean"
property="level" />
</H2>
<H2>Dish bean goes with:
<jsp:getProperty name="pageBean"
property="goesWith" />
</H2>
</BODY></HTML>
34 Java EE training: [Link]

Sharing Beans Example 1:


Result (Initial Request)

35 Java EE training: [Link]


Sharing Beans Example 1:
Result (Later Request)

36 Java EE training: [Link]

Sharing Beans Example 2:


Request-Based Sharing
• Create the bean
– Use jsp:useBean with scope="request".
• Modify the bean
– Use jsp:setProperty with property="*".
– Then, supply request parameters that match the bean
property names.
• Access the bean in the 1st (main) page
– Use jsp:getProperty.
– Then, use jsp:include to invoke the second page.
• Access the bean in the 2nd (included) page
– Use jsp:useBean with the same id as on the first page,
again with scope="request".
– Then, use jsp:getProperty.
37 Java EE training: [Link]
Request-Based Sharing:
Code for Main Page

<BODY>
<H1>Baked Bean Values: request-based Sharing</H1>
<jsp:useBean id="requestBean"
class="[Link]"
scope="request" />
<jsp:setProperty name="requestBean"
property="*" />
<H2>Bean level:
<jsp:getProperty name="requestBean"
property="level" /></H2>
<H2>Dish bean goes with:
<jsp:getProperty name="requestBean"
property="goesWith" /></H2>
<jsp:include page="[Link]" />
38 </BODY></HTML> Java EE training: [Link]

Request-Based Sharing:
Code for Included Page
<H1>Repeated Baked Bean Values:
request-based Sharing</H1>
<jsp:useBean id="requestBean"
class="[Link]"
scope="request" />
<H2>Bean level:
<jsp:getProperty name="requestBean"
property="level" />
</H2>
<H2>Dish bean goes with:
<jsp:getProperty name="requestBean"
property="goesWith" />
</H2>

39 Java EE training: [Link]


Request-Based Sharing:
Result (Initial Request)

40 Java EE training: [Link]

Request-Based Sharing:
Result (Later Request)

41 Java EE training: [Link]


Sharing Beans Example 3:
Session-Based Sharing
• Create the bean
– Use jsp:useBean with scope="session".
• Modify the bean
– Use jsp:setProperty with property="*".
– Then, supply request parameters that match the bean property
names.
• Access the bean in the initial request
– Use jsp:getProperty in the request in which jsp:setProperty is
invoked.
• Access the bean later
– Use jsp:getProperty in a request that does not include request
parameters and thus does not invoke jsp:setProperty. If this request
is from the same client (within the session timeout), the previously
modified value is seen. If this request is from a different client (or
after the session timeout), a newly created bean is seen.
42 Java EE training: [Link]

Session-Based Sharing: Code



<BODY>
<H1>Baked Bean Values: session-based Sharing</H1>
<jsp:useBean id="sessionBean"
class="[Link]"
scope="session" />
<jsp:setProperty name="sessionBean"
property="*" />
<H2>Bean level:
<jsp:getProperty name="sessionBean"
property="level" />
</H2>
<H2>Dish bean goes with:
<jsp:getProperty name="sessionBean"
property="goesWith" />
43 </H2></BODY></HTML> Java EE training: [Link]
Session-Based Sharing: Result
(Initial Request)

44 Java EE training: [Link]

Session-Based Sharing: Result


(Later Request -- Same Client)

45 Java EE training: [Link]


Session-Based Sharing: Result
(Later Request -- New Client)

46 Java EE training: [Link]

Sharing Beans Example 4:


Application-Based Sharing
• Create the bean
– Use jsp:useBean with scope="application".
• Modify the bean
– Use jsp:setProperty with property="*".
– Then, supply request parameters that match the bean property
names.
• Access the bean in the initial request
– Use jsp:getProperty in the request in which jsp:setProperty is
invoked.
• Access the bean later
– Use jsp:getProperty in a request that does not include request
parameters and thus does not invoke jsp:setProperty. Whether this
request is from the same client or a different client (regardless of the
session timeout), the previously modified value is seen.
47 Java EE training: [Link]
Application-Based Sharing:
Code
<BODY>
<H1>Baked Bean Values:
application-based Sharing</H1>
<jsp:useBean id="applicationBean"
class="[Link]"
scope="application" />
<jsp:setProperty name="applicationBean"
property="*" />
<H2>Bean level:
<jsp:getProperty name="applicationBean"
property="level" />
</H2>
<H2>Dish bean goes with:
<jsp:getProperty name="applicationBean"
property="goesWith"/>
48 </H2></BODY></HTML> Java EE training: [Link]

Application-Based Sharing:
Result (Initial Request)

49 Java EE training: [Link]


Application-Based Sharing: Result
(Later Request -- Same Client)

50 Java EE training: [Link]

Application-Based Sharing: Result


(Later Request -- New Client)

51 Java EE training: [Link]


Conditional Bean Operations
• Bean conditionally created
– jsp:useBean results in new bean being instantiated only if
no bean with same id and scope can be found.
– If a bean with same id and scope is found, the preexisting
bean is simply bound to variable referenced by id.
• Bean properties conditionally set
– <jsp:useBean ... />
replaced by
<jsp:useBean ...>statements</jsp:useBean>
– The statements (jsp:setProperty elements) are executed
only if a new bean is created, not if an existing bean is
found.

52 Java EE training: [Link]

Conditional Bean Creation:


AccessCountBean
public class AccessCountBean {
private String firstPage;
private int accessCount = 1;

public String getFirstPage() {


return(firstPage);
}

public void setFirstPage(String firstPage) {


[Link] = firstPage;
}

public int getAccessCount() {


return(accessCount);
}

public void setAccessCountIncrement(int increment) {


accessCount = accessCount + increment;
}
}
53 Java EE training: [Link]
Conditional Bean Creation:
[Link]
<jsp:useBean id="counter"
class="[Link]"
scope="application">
<jsp:setProperty name="counter"
property="firstPage"
value="[Link]" />
</jsp:useBean>
Of [Link] (this page),
<A HREF="[Link]">[Link]</A>, and
<A HREF="[Link]">[Link]</A>,
<jsp:getProperty name="counter" property="firstPage" />
was the first page accessed.
<P>
Collectively, the three pages have been accessed
<jsp:getProperty name="counter" property="accessCount" />
times.
<jsp:setProperty name="counter"
property="accessCountIncrement"
value="1" />
54 Java EE training: [Link]

Accessing SharedCounts1,
SharedCounts2, SharedCounts3
• [Link] was accessed first.
• Pages have been accessed twelve previous
times by an arbitrary number of clients

55 Java EE training: [Link]


Summary
• Benefits of jsp:useBean
– Hides the Java syntax
– Makes it easier to associate request parameters with Java
objects (bean properties)
– Simplifies sharing objects among multiple requests or
servlets/JSPs
• jsp:useBean
– Creates or accesses a bean
• jsp:getProperty
– Puts bean property (i.e. getXxx call) into servlet output
• jsp:setProperty
– Sets bean property (i.e. passes value to setXxx)
56 Java EE training: [Link]

© 2008 Marty Hall

Questions?

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
57 Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like