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