JSP and Beans
JSP and Beans
Overview
z WeatherBean
z Advantages to Using Beans with
JSPs
z Using Beans
z Bean Properties
z Weather Example
z Sharing Beans
z Timer Example
1
WeatherBean
package heidic;
public class WeatherBean
{// Define private properties
private String zipcode;
private int currentTemp;
private int high;
private int low;
private String forecast;
WeatherBean
(cont.)
public WeatherBean()
{ zipcode = "00000";
currentTemp = 0;
high = 0;
low = 0;
forecast = "Not available.";
}
2
WeatherBean
(cont.)
public String getZipcode()
{ return zipcode; }
public void setZipcode(
String zip)
{ zipcode = zip; }
WeatherBean
(cont.)
public int getHigh()
{ return high; }
3
WeatherBean
(cont.)
public void update(String z)
{ zipcode = z;
if (zipcode.equals("06120"))
{
currentTemp = 70;
high = 72;
low = 50;
forecast = "Cloudy";
}
7
WeatherBean
(cont.)
else if(zipcode.equals("11111"))
{ currentTemp = 30;
high = 32;
low = 10;
forecast = "Snowy";
}else if(zipcode.equals("22222"))
{ currentTemp = 90;
high = 92;
low = 80;
forecast = "Sunny"; }
8
4
WeatherBean
(cont.)
else {
currentTemp = 70;
high = 72;
low = 50;
forecast = "Cloudy"; }
}
}
10
5
Advantages to Beans and JSPs
(cont.)
3. Convenient mapping between
request parameters and object
properties.
z Bean constructs simplify the loading
of beans
11
6
Using Beans With JSPs
(cont.)
z Beans are loaded into a JSP page
using the <jsp:useBean> action:
<jsp:useBean id=“beanname”
class=“package.Class” />
<jsp:useBean id=“wBean”
class=“heidic.WeatherBean” />
z (Usually) tells server to create
instance of bean and bind to id name.
Variable is in _jspService method of
servlet
13
14
7
Using Beans With JSPs
(cont.)
2. class - specifies class name of
JavaBean.
Required
Usually includes package designation
15
<jsp:useBean id=”mythread”
class=”MyClass”
type=”Runnable” />
16
8
Using Beans With JSPs
(cont.)
4. beanName - used like class attribute
to refer to a bean.
Can refer either to class or to file
containing serialized bean object
5. scope - controls a bean’s
accessibility and life span.
Valid values: page, request, session,
and application
17
Bean Properties
<jsp:getProperty name=”beanname”
property=”propname”/>
<jsp:getProperty name=”wBean”
property=”zipcode” />
18
9
Bean Properties
(cont.)
z beanname is name of bean.
z property must match property name
defined in bean.
Case sensitive
z Must have previously created the
bean via <jsp:useBean>
19
Bean Properties
(cont.)
<jsp:useBean id=”style”
class=”beans.MyStyle” />
<html>
<body bgcolor=”
<jsp:getProperty
name=”style”
property=”color”/> “ >
20
10
Bean Properties
(cont.)
<center>
<img src=”
<jsp:getProperty
name=”style”
property=”logo”/> “ >
</center>
</body>
</html>
21
Bean Properties
(cont.)
<html>
<body bgcolor=”red “ >
<center>
<img src=”
http:\\www.mycorp.com\
logo.gif “ >
</center>
</body>
</html>
22
11
Bean Properties
(cont.)
z Note that we can use our bean
variable in a JSP expression.
Provides us two ways of retrieving data
When would we use each approach?
<jsp:getProperty
name=”book”
property=”title” / >
<%= book.getTitle() %>
23
Bean Properties
(cont.)
z To modify a bean’s properties use:
<jsp:setProperty
name=”beanName”
property=”beanprop”
value=“newvalue” / >
<jsp:setProperty
name=”wBean”
property=”high”
value=“90” / >
24
12
Bean Properties
(cont.)
z Developer must have provided
appropriate “set” method for
property.
z Could also use:
<% wBean.setHigh(90); %>
z Bean action tags are evaluated from
top to bottom of page.
25
Bean Properties
(cont.)
z Property values can be initialized
when creating a bean:
<jsp:useBean id =”wBean”
class=”heidic.WeatherBean”>
<jsp:setProperty
name=”weatherBean”
property=”zipcode”
value=”06120” />
</jsp:useBean>
26
13
Bean Properties
(cont.)
z The value and name attributes of
setProperty may hold request-time
expressions.
Use mix of single and double quotes
<jsp:setProperty
name=”wBean”
property=”zipcode”
value=’<%= request.
getParameter(“zip”) %>’ />
27
Bean Properties
(cont.)
z The param attribute may be used to
directly associate a name to a form
input parameter.
Used in place of the value parameter
Parameter value automatically used as
value of property
Simple type conversions performed
automatically
param must exactly match input name
28
14
Bean Properties
(cont.)
<jsp:setProperty name=”wBean”
property=”currentTemp”
param=”currentTemp”/>
z Can be simplified if form element
name and bean property match
exactly:
<jsp:setProperty name=”wBean”
param=”currentTemp”/>
29
Bean Properties
(cont.)
z Automatic conversion supported for:
boolean, Boolean, byte, Byte,
char, Character, double, Double,
int, Integer, float, Float,
long, Long
z Associate all properties with
identically named input parameters:
Supply “*” for property parameter.
<jsp:setProperty name=”entry”
param=”*”/>
30
15
Bean Properties
Cautions
1. System does not supply null for
missing input parameters.
z Best to provide default value and
then attempt to set from parameter:
<jsp:setProperty name=”wBean”
property=”currentTemp”
value=”0”/>
<jsp:setProperty name=”Bean”
param=”currentTemp”/>
31
Bean Properties
Cautions (cont.)
2. Automatic type conversion does not
guard against illegal values as
effectively as manual type
conversion.
3. Property names and input
parameters are case sensitive.
32
16
Weather Example
http://www.rh.edu/~heidic/
webtech/examples.html
33
Weather Example
weatherform.html
<html> <head>
<title> Heidi's Simple Page
to Test Beans and JSPs</title>
</head>
<body bgcolor="white">
<h1> Testing Beans and JSPs
</h1>
When user enters their ...
34
17
Weather Example
weatherform.html (cont.)
<ul>
<li> 06120 (Hartford) </li>
<li> 11111 (Nome) </li>
<li> 22222 (Hawaii) </li>
</ul>
<form action="http://
facweb1.rh.edu/users/heidic/
jsp/weather.jsp">
35
Weather Example
weatherform.html (cont.)
Enter a new zipcode:
<input type="text" name="zip">
<input type="submit"
value="Submit your entry.">
<input type="reset"
value="Clear your entry.">
</form>
</body> </html>
36
18
Weather Example
weather.jsp
<html> <head>
<title> Heidi's Simple
Beans Test </title>
</head>
<body bgcolor="white">
<center>
<h1> Heidi's Test Page for
Simple Beans </h1>
</center>
37
Weather Example
weather.jsp (cont.)
<h2>
This page tests using a simple
Weather JavaBean with a JSP.
</h2>
<jsp:useBean id="weatherBean"
scope="page"
class="heidic.WeatherBean" />
38
19
Weather Example
weather.jsp (cont.)
<ul>
<li> Initial value of zipcode:
<jsp:getProperty
name="weatherBean"
property="zipcode" />
<li> Initial value of current
temperature:
<jsp:getProperty
name="weatherBean"
property="currentTemp" />
39
Weather Example
weather.jsp (cont.)
<li> High temperature:
<jsp:getProperty
name="weatherBean"
property="high" />
<li> Low temperature:
<jsp:getProperty
name="weatherBean"
property="low" />
40
20
Weather Example
weather.jsp (cont.)
<li> Forecast:
<jsp:getProperty
name="weatherBean"
property="forecast" />
</ul>
<% weatherBean.update(
request.getParameter("zip"));%>
<h3>
. . after updating the weather:
41
Weather Example
weather.jsp (cont.)
<ul>
<li> New value of zipcode:
<jsp:getProperty
name="weatherBean"
property="zipcode" />
<li> Current temperature:
<jsp:getProperty
name="weatherBean"
property="currentTemp" />
42
21
Weather Example
weather.jsp (cont.)
<li> High temperature:
<jsp:getProperty
name="weatherBean"
property="high" />
<li> Low temperature:
<jsp:getProperty
name="weatherBean"
property="low" />
43
Weather Example
weather.jsp (cont.)
<li> Forecast:
<jsp:getProperty
name="weatherBean"
property="forecast" />
</ul>
</body>
</html>
44
22
Sharing Beans
Sharing Beans
page Scope
1. page - default value.
z Least accessible and shortest lived.
z New instance of bean is created each
time page is requested.
z Beans not available to included or
forwarded pages.
z Good when bean does not need to
persist between requests.
z Good when bean does not need to be
shared.
46
23
Sharing Beans
page Scope (cont.)
z Bean object is placed in
PageContext object for duration of
current request.
z Beans can be retrieved by calling
getAttribute on pageContext
within servlet.
<jsp:useBean
id="weatherBean" scope="page"
class="heidic.WeatherBean" />
47
Sharing Beans
request Scope
2. request
z Accessibility extended to included
and forwarded pages
z Bean put on HttpServletRequest
object for duration of request.
Also being bound to local variable
Access by servlet is via setAttribute
on HttpServletRequest
z Allows servlet to create a bean and
pass it to JSP page.
48
24
Sharing Beans
session Scope
3. session
z Bean is placed in user’s session
object (HttpSession).
Page must be participating in sessions
If not, causes error at translation time
z Access by servlet via
session.getAttribute method.
z Bean is available to any other JSP or
servlet on server.
<jsp:useBean> finds existing bean
that matches id
49
Sharing Beans
session Scope (cont.)
z JSP container determines length of
time a session bean exists.
Typically a few hours
z Session beans useful for:
Collecting information through a user’s
visit to site
Caching information frequently needed
at page level
Passing information from page to page
with low processing time
50
25
Sharing Beans
application Scope
4. application
z Broadest lifecycle and availability.
z Stores information useful across
entire application.
z Beans are associated with a given
JSP application on server.
z Stored in ServletContext object.
Retrieved by servlet via
application.getAttribute method
z Exist for life of JSP container.
i.e., until server shuts down
51
Sharing Beans
application Scope (cont.)
z Bean shared by all application users.
Must not depend on configuration of
any page
Changing a property will instantly affect
all JSP pages which reference the bean
Make sure that bean is placed into
application scope before any
dependent beans
z Application bean provides simple
mechanism for multiple servlets and
JSPs to access the same object.
52
26
Timer Example
http://www.rh.edu/~heidic/
webtech/examples.html
53
Timer Example
TimerBean.java
package heidic;
public class TimerBean
{
private long startTime;
public TimerBean()
{startTime =
System.currentTimeMillis();
}
54
27
Timer Example
TimerBean.java (cont.)
public long getElapsedMillis()
{long now =
System.currentTimeMillis();
return now - startTime;
}
public long getElapsedSeconds()
{ return (long)this.
getElapsedMillis()/1000;
}
55
Timer Example
TimerBean.java (cont.)
public long getElapsedMinutes()
{return (long)this.
getElapsedMillis()/60000;
}
public void reset()
{startTime =
System.currentTimeMillis();
}
56
28
Timer Example
TimerBean.java (cont.)
public long getStartTime()
{ return startTime; }
public void
setStartTime(long time)
{if (time < 0)
reset();
else startTime = time;
} } //End of class
57
Timer Example
starttimer.jsp
<html> <head>
<title> Heidi's Sharing
Beans Test </title>
</head>
<body bgcolor="white">
<center>
<h1> Heidi's Test for
Sharing Beans with JSP </h1>
</center>
58
29
Timer Example
starttimer.jsp (cont.)
<h2>This page tests starting a
Timer bean from a JSP.</h2>
<jsp:useBean id="timerBean"
scope="session"
class="heidic.TimerBean" >
<jsp:setProperty
name="timerBean"
property="startTime"
value="-1" />
</jsp:useBean>
59
Timer Example
starttimer.jsp (cont.)
Elapsed time (minutes):
<jsp:getProperty
name="timerBean"
property="elapsedMinutes" />
Elapsed time (seconds):
<jsp:getProperty
name="timerBean"
property="elapsedSeconds" />
</body> </html>
60
30
Timer Example
usetimer.jsp
<html> <head>
<title> Heidi's Sharing Beans
Test </title>
</head>
<body bgcolor="white">
<center>
<h1> Heidi's Test for Sharing
Beans with JSP </h1>
</center>
61
Timer Example
usetimer.jsp (cont.)
<h2>Page tests sharing existing
Timer bean from a JSP.</h2>
<jsp:useBean
id="timerBean" scope="session“
class="heidic.TimerBean" />
Current elapsed seconds:
<jsp:getProperty
name="timerBean"
property="elapsedSeconds" />
62
31
Timer Example
usetimer.jsp (cont.)
</body>
</html>
63
Workshop 1
JSP and Beans
z Create an JSP which loads
information into a JavaBean and
redisplays the information.
1. Create a JSP that prompts the user
for their name and address.
2. Within the JSP, create a JavaBean to
hold the name and address.
3. Redisplay the name and address
information from the JavaBean later
in the JSP.
64
32