CISH-6510 Web Application Design and Development JSP and Beans
Overview z z z z z z z
WeatherBean Advantages to Using Beans with JSPs Using Beans Bean Properties Weather Example Sharing Beans Timer Example
2
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; 3
WeatherBean (cont.) public WeatherBean() { zipcode = "00000"; currentTemp = 0; high = 0; low = 0; forecast = "Not available."; } 4
2
WeatherBean (cont.) public String getZipcode() { return zipcode; } public void setZipcode( String zip) { zipcode = zip; } public int getCurrentTemp() { return currentTemp; } 5
WeatherBean (cont.) public int getHigh() { return high; } public int getLow() { return low;
}
public String getForecast() { return forecast; } 6
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"; } } }
9
Advantages to Beans and JSPs 1.
Java syntax is hidden. z Page authors can manipulate Java using XML syntax only z Stronger separation between content and presentation z Useful when developing with separate teams of HTML and Java developers
2.
Simpler object sharing. z Easy to share beans across pages in application 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
Using Beans With JSPs z
Beans are placed into a JSP page using three Bean tags: <jsp:useBean> <jsp:setProperty> <jsp:getProperty>
z
JSP also supports custom tags to provide more complex functionality. More in another segment 12
6
Using Beans With JSPs (cont.) 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. z
Variable is in _jspService method of servlet 13
Using Beans With JSPs (cont.) z 1.
useBean tag has attributes: id - specifies unique name for bean. Required Must be unique to the page in which it is defined Is case sensitive First character must be a letter Only letters, numbers, and underscore allowed ¾ no spaces 14
7
Using Beans With JSPs (cont.) 2.
class - specifies class name of JavaBean. Required Usually includes package designation
15
Using Beans With JSPs (cont.) 3.
type - allows you to refer to the bean using a base class of the bean or an interface that the bean implements. Throws ClassCastException if actual class is not compatible with type Not highly used
<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 z
Once you have a bean, you can access its properties using the <jsp:getProperty> action:
<jsp:getProperty name=”beanname” property=”propname”/> <jsp:getProperty name=”wBean” property=”zipcode” /> 18
9
Bean Properties (cont.) z z
beanname is name of bean. 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” /> “ >
20
10
Bean Properties (cont.)
“ > 21
Bean Properties (cont.)
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
z
Developer must have provided appropriate “set” method for property. 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” /> 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. z
System does not supply null for missing input parameters. 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.
3.
Automatic type conversion does not guard against illegal values as effectively as manual type conversion. Property names and input parameters are case sensitive.
32
16
Weather Example z
Look at “Weather” JSP example at: http://www.rh.edu/~heidic/ webtech/examples.html
33
Weather Example weatherform.html
Heidi's Simple Page to Test Beans and JSPs Testing Beans and JSPs
When user enters their ... 34
17
Weather Example weatherform.html (cont.)
- 06120 (Hartford)
- 11111 (Nome)
- 22222 (Hawaii)
36
18
Weather Example weather.jsp
Heidi's Simple Beans Test Heidi's Test Page for Simple Beans
37
Weather Example weather.jsp (cont.)
This page tests using a simple Weather JavaBean with a JSP.
<jsp:useBean id="weatherBean" scope="page" class="heidic.WeatherBean" />
38
19
Weather Example weather.jsp (cont.)
- Initial value of zipcode: <jsp:getProperty name="weatherBean" property="zipcode" />
- Initial value of current temperature: <jsp:getProperty name="weatherBean" property="currentTemp" /> 39
Weather Example weather.jsp (cont.) - High temperature: <jsp:getProperty name="weatherBean" property="high" />
- Low temperature: <jsp:getProperty name="weatherBean" property="low" /> 40
20
Weather Example weather.jsp (cont.) - Forecast: <jsp:getProperty name="weatherBean" property="forecast" />
<% weatherBean.update( request.getParameter("zip"));%>
. . after updating the weather: 41
Weather Example weather.jsp (cont.) - New value of zipcode: <jsp:getProperty name="weatherBean" property="zipcode" />
- Current temperature: <jsp:getProperty name="weatherBean" property="currentTemp" /> 42
21
Weather Example weather.jsp (cont.) - High temperature: <jsp:getProperty name="weatherBean" property="high" />
- Low temperature: <jsp:getProperty name="weatherBean" property="low" /> 43
Weather Example weather.jsp (cont.) - Forecast: <jsp:getProperty name="weatherBean" property="forecast" />
44
22
Sharing Beans z
Up to this point, we’ve treated beans as local variables. Every time page is requested, new instance of bean is created and used
z
The scope attribute controls bean’s accessibility and life span. Determines which pages or parts of a Web application can access the bean Determines how long a bean exists
z
scope has four possible values: 45
Sharing Beans page Scope 1. z z z z z
page - default value. Least accessible and shortest lived. New instance of bean is created each time page is requested. Beans not available to included or forwarded pages. Good when bean does not need to persist between requests. Good when bean does not need to be shared. 46
23
Sharing Beans page Scope (cont.) z
z
Bean object is placed in PageContext object for duration of current request. 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. z z
request Accessibility extended to included and forwarded pages 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. z
session Bean is placed in user’s session object (HttpSession). Page must be participating in sessions If not, causes error at translation time
z z
Access by servlet via session.getAttribute method. 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. z z z z
application Broadest lifecycle and availability. Stores information useful across entire application. Beans are associated with a given JSP application on server. 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 z
Look at “Timer” JSP example at: 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 Heidi's Sharing Beans Test Heidi's Test for Sharing Beans with JSP
58
29
Timer Example starttimer.jsp (cont.) This page tests starting a Timer bean from a JSP.
<jsp:useBean id="timerBean" scope="session" class="heidic.TimerBean" > <jsp:setProperty name="timerBean" property="startTime" value="-1" /> 59
Timer Example starttimer.jsp (cont.) Elapsed time (minutes): <jsp:getProperty name="timerBean" property="elapsedMinutes" /> Elapsed time (seconds): <jsp:getProperty name="timerBean" property="elapsedSeconds" /> 60
30
Timer Example usetimer.jsp Heidi's Sharing Beans Test Heidi's Test for Sharing Beans with JSP
61
Timer Example usetimer.jsp (cont.) Page tests sharing existing Timer bean from a JSP.
<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.) Elapsed time (minutes): <jsp:getProperty name="timerBean" property="elapsedMinutes" />
63
Workshop 1 JSP and Beans z
1. 2. 3.
Create an JSP which loads information into a JavaBean and redisplays the information. Create a JSP that prompts the user for their name and address. Within the JSP, create a JavaBean to hold the name and address. Redisplay the name and address information from the JavaBean later in the JSP. 64
32