Using Javabeans G in JSP: For Live Java Ee Training, Please See Training Courses
Using Javabeans G in JSP: For Live Java Ee Training, Please See Training Courses
Using
g JavaBeans
in JSP
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name.
Note 2: property name is derived only from method name. Instance variable name is irrelevant.
public
bli ddouble
bl getSpeed()
d() {
return(speed);
}
public
bli void
id setSpeed(double
tS d(d bl newSpeed)
S d) {
speed = newSpeed;
}
• Y
You should
h ld do
d this
thi in
i all
ll your Java
J code
d
anyhow. Why?
9
Why You Should Use
Accessors Not Public Fields
Accessors,
• 1) You can put constraints on values
public void setSpeed(double newSpeed) {
if (newSpeed < 0) {
sendErrorMessage(...);
newSpeed = Math.abs(newSpeed);
}
speed = newSpeed;
}
10
public
p blic void
oid setSpeedInKPH(do
setSpeedInKPH(double
ble ne
newSpeed)
Speed) {
speedInKPH = newSpeed;
}
11
Why You Should Use
Accessors Not Public Fields
Accessors,
• 3) You can perform arbitrary side effects
public double setSpeed(double newSpeed) {
speed = newSpeed;
updateSpeedometerDisplay();
}
12
17
Example: StringBean
package coreservlets;
public class StringBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message
hi = message;
}
}
• Beans installed in normal Java directory
– MyEclipse: src/folderMatchingPackage
p y
– Deployment: WEB-INF/classes/folderMatchingPackage
f g g
• Beans must always be in packages!
18
20
<jsp:setProperty
j p p y
name="entry"
property="itemID"
q g
value='<%= request.getParameter("itemID") %>' />
21
Setting Bean Properties Case 1:
Explicit Conversion & Assignment
<%
int numItemsOrdered = 1;
try {
numItemsOrdered =
Integer parseInt(request getParameter("numItems"));
Integer.parseInt(request.getParameter( numItems ));
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty
jsp:set ope ty
name="entry"
property="numItems"
value="<%= numItemsOrdered %>" />
/
22
<%--
% setDiscountCode
set scou tCode e
expects
pects a doub
double
e --%>
%
<jsp:setProperty
y
name="entry"
property="discountCode"
value="<%= discountCode %>" />
23
Setting Bean Properties Case 1:
Explicit Conversion & Assignment
24
25
Case 2: Associating Individual
Properties with Input Parameters
<jsp:useBean id="entry"
class="coreservlets SaleEntry" />
class="coreservlets.SaleEntry"
<jsp:setProperty
name="entry"
property="itemID"
param="itemID" />
<jsp:setProperty
name="entry"
property="numItems"
param="numItems" /
p />
<jsp:setProperty
name="entry"
property= discountCode
property="discountCode"
param="discountCode" />
26
27
Case 3: Associating All Properties
with Input Parameters
<jsp:useBean id="entry"
class="coreservlets.SaleEntry"
l " l t S l E t " />
<jsp:setProperty name="entry" property="*" />
28
Sharing Beans
• You can use the scope attribute to specify
additional
ddi i l places
l where
h bean
b is
i storedd
– Still also bound to local variable in _jspService
– <jsp:useBean id="
id="…" " class="
class="…" "
scope="…" />
• Lets multiple
p servlets or JSP pages
p g
share data
• Also permits conditional bean creation
– Creates new object only if it can't find existing one
29
Sharing Beans: Example
• page1.jsp
<jsp:useBean
j B id "f " class="…"
id="foo" l " " scope="application"/>
" li i "/
<jsp:setProperty name="foo" property="message"
value="Hello"/>
<jsp:getProperty name="foo" property="message"/>
• page2.jsp
<jsp:useBean
jp id="foo" class="…" scope="application"/>
p pp
<jsp:getProperty name="foo" property="message"/>
• Possible scenario 1
– JJoe goes tto page 2 ((output
t t is
i "Default
"D f lt Message")
M ")
– 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")
30
31
Values of the scope Attribute
• session
( j
(<jsp:useBean
B … scope="session"/>)
" i "/ )
– Bean will be stored in the HttpSession object associated
with the current request,
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
32
• Important:
– Use different names (i.e.,
(i e id in jsp:useBean) for different
beans
33 • Don't store beans in different places with same id
Sharing Beans Four Ways:
Bean Code
package coreservlets;
…
public class BakedBean implements Serializable {
private String level = "half-baked";
private String goesWith = "hot dogs";
35
Sharing Beans Example 1:
Page-Scoped (Unshared)
…
<BODY>
<H1>Baked Bean Values: page-based Sharing</H1>
<jsp:useBean id="pageBean"
class="coreservlets BakedBean" />
class="coreservlets.BakedBean"
<jsp:setProperty name="pageBean" property="*" />
<H2>Bean level:
<j
<jsp:getProperty
tP t name="pageBean"
" B "
property="level" />
</H2>
<H2>Dish
2 bean goes with:
<jsp:getProperty name="pageBean"
property="goesWith" />
</H2>
</BODY></HTML>
36
37
Sharing Beans Example 1:
Result (Later Request)
38
Request-Based Sharing:
Code for Included Page
<H1>Repeated Baked Bean Values:
request-based Sharing</H1>
<jsp:useBean id="requestBean"
class="coreservlets.BakedBean"
scope="request" />
<H2>Bean level:
<jsp:getProperty name="requestBean"
property="level"
t "l l" />
</H2>
<H2>Dish bean goes with:
<jsp:getProperty name="requestBean"
property="goesWith" />
</H2>
41
Request-Based Sharing:
Result (Initial Request)
42
Request-Based Sharing:
Result (Later Request)
43
Sharing Beans Example 3:
Session-Based Sharing
• Create the bean
– Use
U jjsp:useBean
B with
i h scope="session".
" i "
• Modify the bean
– Use jjsp:setProperty
p p y with property="*".
p p y
– 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),
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.
44
46
47
Session-Based Sharing: Result
(Later Request -- New Client)
48
Application-Based Sharing:
Result (Initial Request)
51
Application-Based Sharing: Result
(Later Request -- Same Client)
52
53
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,
found the preexisting
bean is simply bound to variable referenced by id.
• Bean p
properties
p conditionally
y set
– <jsp:useBean ... />
replaced by
<jsp:useBean ...>statements</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.
54
Accessing SharedCounts1,
SharedCounts2 SharedCounts3
SharedCounts2,
• SharedCounts2.jsp was accessed first.
• Pages have been accessed twelve previous
times by an arbitrary number of clients
57
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
j B
– Creates or accesses a bean
• jsp:setProperty
– Sets bean property (i.e. passes value to setXxx)
• You usually
y use p
property="*"
p y to p
pass in request
q params
p
• jsp:getProperty
58
– Puts bean property (i.e. getXxx call) into servlet output
Questions?