CISH-6510 Web Application Design and Development JSP and Beans

Overview
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.
Page authors can manipulate Java using XML syntax only Stronger separation between content and presentation Useful when developing with separate teams of HTML and Java developers

2.

Simpler object sharing.
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.
Bean constructs simplify the loading of beans

11

Using Beans With JSPs
Beans are placed into a JSP page using three Bean tags: <jsp:useBean> <jsp:setProperty> <jsp:getProperty> 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” /> (Usually) tells server to create instance of bean and bind to id name.
Variable is in _jspService method of servlet
13

Using Beans With JSPs (cont.)
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
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.)
beanname is name of bean. property must match property name defined in bean.
Case sensitive

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.)
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.)
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.)
Developer must have provided appropriate “set” method for property. Could also use: <% wBean.setHigh(90); %> Bean action tags are evaluated from top to bottom of page.
25

Bean Properties (cont.)
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.)
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.)
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”/> Can be simplified if form element name and bean property match exactly: <jsp:setProperty name=”wBean” param=”currentTemp”/>
29

Bean Properties (cont.)
Automatic conversion supported for:
boolean, Boolean, byte, Byte, char, Character, double, Double, int, Integer, float, Float, long, Long

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. 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
Look at “Weather” JSP example at: 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
Up to this point, we’ve treated beans as local variables.
Every time page is requested, new instance of bean is created and used

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

scope has four possible values:
45

Sharing Beans page Scope
1.

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.)
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.

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

Allows servlet to create a bean and pass it to JSP page.
48

24

Sharing Beans session Scope
3.

session Bean is placed in user’s session object (HttpSession).
Page must be participating in sessions If not, causes error at translation time

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.)
JSP container determines length of time a session bean exists.
Typically a few hours

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 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

Exist for life of JSP container.
i.e., until server shuts down
51

Sharing Beans application Scope (cont.)
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

Application bean provides simple mechanism for multiple servlets and JSPs to access the same object.
52

26

Timer Example
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
<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.)
Elapsed time (minutes): <jsp:getProperty name="timerBean" property="elapsedMinutes" /> </body> </html>

63

Workshop 1 JSP and Beans
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

1. 2. 3.

32

Sign up to vote on this title
UsefulNot useful