1.13k likes | 1.18k Views
Learn how to implement dynamic web pages using JavaServer Faces (JSF) technology and build three-tier web applications. Understand the syntactical elements of JSF and navigation in JSF applications.
E N D
Chapter Goals • To implement dynamic web pages with JavaServer Faces (JSF) technology • To learn the syntactical elements of JavaServer Faces • To learn about navigation in JSF applications • To build three-tier web applications
A Simple JSF Program • JSF: Java Server Faces • To develop a JSF application, you need a web server that is integrated with a JSF container • A JSF page contains HTML and JSF tags • The user interface of a JSF application is described by a set of JSF pages
A Simple JSF Program • Each JSF page has the following structure: <html> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <f:view> <head> <title>Page title</title> </head> <body> <h:form> Page contents </h:form> </body> </f:view> </html>
A Simple JSF Program • Previous structure has three parts: • taglib directives required to locate two JSF libraries • Tags from the core library have the prefix f: (such as f:view) • Tags from the HTML library have the prefix h: (such as h:form) • All JSF tags must be contained inside an f:view tag • The h:form tag encloses all user interface elements
Executing the datetime Web Application Figure 1:Executing the datetime Web Application
File datetime/index.jsp 01:<html> 02: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 03: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 04: 05: <f:view> 06: <head> 07: <title>The datetime application</title> 08: </head> 09: <body> 10: <h:form> 11: <p>Number of milliseconds since January 1, 1970: 12: <h:outputText value="#{dateTime.time}"/> 13: </p> 14: </h:form> 15: </body> 16: </f:view> 17:</html>
The JSF Container Rewrites the Requested Page Figure 2:The JSF Container Rewrites the Requested Page
A Simple JSF Program • Purpose of a JSF page is to generate an HTML page • Basic process: • HTML tags in the page are retained; they are the static part of the page • JSF tags are translated into HTML; translation is dynamic, it depends on the state of Java objects • The h: tags generate HTML • The f: describe structural information that the h: tags use • The taglib directives are stripped out
The HTML Code That Is Generated by a JSF Page Figure 3:The HTML Code That Is Generated by a JSF Page
A Simple JSF Program • The JSF container converts a JSF page to an HTML page, replacing JSF tags with text and HTML • In the example, the h:outputText tag has the value binding #{dateTime.time} • Value bindings link JSF pages with Java objects Continued
A Simple JSF Program • The Java objects are defined in a configuration file • Named faces-config.xml • Placed in the WEB-INF subdirectory of the web application's base directory
File datetime/WEB-INF/faces-config.xml 01:<?xml version="1.0"?>02: 03:<!DOCTYPE faces-config PUBLIC 04: "-//Sun Microsystems, Inc. //DTD JavaServer Faces Config 1.0//EN" 05: "http://java.sun.com/dtd/web-facesconfig_1_0.dtd"> 06: 07:<faces-config> 08: <managed-bean> 09: <managed-bean-name>dateTime</managed-bean-name> 10: <managed-bean-class>java.util.Date</managed-bean-class> 11: <managed-bean-scope>request</managed-bean-scope> 12: </managed-bean>13: </faces-config>
A Simple JSF Program • This file defines an object dateTime with type java.util.Date • A new object is constructed with each "request" • Whenever a browser requests the page, • A new Date object is constructed, and • It is attached to the dateTime variable • The Date constructor constructs an object with the current time Continued
A Simple JSF Program • #{dateTime.time} calls getTime of dateTime • The h:outputText tag converts the result of that method call to text
Important Design Principle of the JSF Technology • JSF enables the separation of presentation and business logic • Presentation logic: the user interface of the web application • Business logic: the part of the application that is independent of the visual presentation • JSF pages define the presentation logic • Java objects define the business logic • The value bindings tie the two together
Steps for Deploying a JSF Application • Make a subdirectory with the name of your web application in the webapps directory of your Tomcat installation or • Place the index.jsp file into that directory /usr/local/jakarta-tomcat/webapps/datetime c:\Tomcat\webapps\datetime Continued
Steps for Deploying a JSF Application • Create a subdirectory WEB-INF in your application directory or /usr/local/jakarta-tomcat/webapps/datetime c:\Tomcat\webapps\datetime\WEB-INF
Steps for Deploying a JSF Application • Place faces-config.xml into the WEB-INF subdirectory • Place your Java classes (if any) inside WEB-INF/classes • Place the file web.xml inside the WEB-INF subdirectory • Start the web server • Point your browser to http://localhost:8080/datetime/index.faces
The Directory Structure of the datetimeApplication Figure 4:The Directory Structure of the datetime Application
The Java Studio Creator Tool Figure 5:The Java Studio Creator Tool
File datetime/WEB-INF/web.xml 01:<?xml version="1.0"?> 02: 03:<!DOCTYPE web-app PUBLIC 04: "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 05:"http://java.sun.com/dtd/web-app_2_3.dtd"> 06: 07:<web-app> 08: <servlet> 09: <servlet-name>Faces Servlet</servlet-name> 10: <servlet-class>javax.faces.webapp.FacesServlet </servlet-class> 11: <load-on-startup>1</load-on-startup> 12: </servlet> 13: 14: <servlet-mapping> 15: <servlet-name>Faces Servlet</servlet-name> 16: <url-pattern>*.faces</url-pattern> 17: </servlet-mapping> 18:</web-app>
Self Check • What steps are required to add the image of a clock to the datetime application? (The clock doesn't have to show the correct time.) • Does a Swing program automatically separate presentation and business logic?
Answers • Place an image file, say clock.gif, into the datetime directory, and add a tag <img src="clock.gif"/> to the index.jsp file. • No–it is possible (and sadly common) for programmers to place the business logic into the frame and component classes of the user interface.
JavaBeans Components • Software component: • Encapsulates functionality • Can be plugged into a software system without programming • For example, the dateTime object • Unlike some programming languages, Java does have explicit support for components Continued
JavaBeans Components • In Java, use a programming convention to implement components • A JavaBean is a Java class that follows this convention • A JavaBean exposes properties–values of the component that can be accessed without programming
JavaBeans Components • JavaBean requirements: • Must have a public constructor with no parameters • Must have methods for accessing the component properties that follow the get/set naming convention
JavaBeans Components • For example, to get or set the time of a Date object, must use getTime and setTime • For a property with name propertyName and type Type, • Exception: the accessor of a boolean property can use an is prefix public Type getPropertyName() public void setPropertyName(Type newValue) public boolean isShopping()
JavaBeans Components • The name of a property starts with a lowercase letter • The corresponding methods have an uppercase letter (isShopping) • Exception: property names can be all capitals (e.g. ID or URL) • getID or setURL Continued
JavaBeans Components • Read-only property: has only a get method • Write-only property: has only a set method • A JavaBean can have additional methods, but they are not connected with properties
JavaBeans Components • Many programmers follow the additional convention that the name of a bean class should end in Bean Continued
JavaBeans Components public class UserBean { // Required default constructor public UserBean() { . . . } // creditCard property public String getCreditCard() { . . . } public void setCreditCard(String newValue) { . . . } // shopping property public boolean isShopping() { . . . } public void setShopping(boolean newValue) { . . . } // Other methods . . . // Instance fields . . . } Continued
JavaBeans Components • This bean has two properties: creditCardand shopping • Do not make any assumptions about the internal representation of properties • May have an instance field for every property: private String creditCard; private boolean shopping; Continued
JavaBeans Components • Do not make any assumptions about the internal representation of properties • May store the credit card state in a database • get and set methods would contain database operations • May compute the property value: public boolean isShopping() { return shoppingCart != null; }
JavaBeans Components • To use a bean in a JSF page, define it in faces-config.xml • Called a managed bean because the JSF container manages its lifetime <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>bigjava.UserBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> Continued
JavaBeans Components • Session scope: the bean is available for multiple requests by the same browser • Application scope: the bean stays alive for the entire web application • It is shared among different users
JavaBeans Components • Access the bean properties in value bindings • Specify the name of the property, not the name of the get or set methods • <h:inputText value="#{user.creditCard}"/> first callsgetCreditCard • When the user submits the form, the setCreditCard is called to store the edited property value <h:outputText value="#{user.creditCard}"/>
JavaBeans Components: An Example • We want to display the current time, not the number of milliseconds since January 1, 1970 • Default time computation uses the time zone at the server location → not very useful • We will prompt for the city in which the user is located, and display the time in the user's time zone
JavaBeans Components: An Example • Java library contains a TimeZone class • A time zone is identified by a string such as "America/Los_Angeles" or "Asia/Tokyo" • getAvailableIDs returns a string array containing all IDs: • getTimeZone returns a TimeZone object for a given ID string: String[] ids = TimeZone.getAvailableIDs(); String id = "America/Los_Angeles"; TimeZone zone = TimeZone.getTimeZone(id);
JavaBeans Components: An Example • Use a DateFormat object to get a time string: DateFormat timeFormatter = DateFormat.getTimeInstance(); timeFormatter.setTimeZone(zone); Date now = new Date(); // Suppose the server is in New York, and it's noon there System.out.println(timeFormatter.format(now)); // Prints 9:00:00 AM
JavaBeans Components: An Example • Interaction with user: • The user will simply enter the city name • The time zone bean will replace the spaces in the name with underscores • Then, check if that string appears at the end of one of the valid time zone IDs
The timezone Application Figure 6:The timezone Application
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 01:package bigjava; 02: 03:import java.text.DateFormat; 04:import java.util.Date; 05:import java.util.TimeZone; 06: 07: /** 08: This bean formats the local time of day for a given date 09: and city. 10: */ 11:public class TimeZoneBean 12:{ 13: /** 14: Initializes the formatter. 15: */ Continued
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 16:public TimeZoneBean() 17: { 18: timeFormatter = DateFormat.getTimeInstance(); 19: } 20: 21: /** 22: Setter for city property. 23: @param aCity the city for which to report the // local time 24: */ 25:public void setCity(String aCity) 26: { 27: city = aCity; 28: zone = getTimeZone(city); 29: } 30: Continued
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 31: /** 32: Getter for city property. 33: @return the city for which to report the local time 34: */ 35: public String getCity() 36: { 37:return city; 38: } 39: 40: /** 41: Read-only time property. 42: @return the formatted time 43: */ 44:public String getTime() 45: { Continued
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 46:if (zone == null) return"not available"; 47: timeFormatter.setTimeZone(zone); 48: Date time = new Date(); 49: String timeString = timeFormatter.format(time); 50:return timeString; 51: } 52: 53: /** 54: Looks up the time zone for a city 55: @param aCity the city for which to find the time zone 56: @return the time zone or null if no match is found 57: */ 58:private static TimeZone getTimeZone(String city) 59: { Continued
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 60: String[] ids = TimeZone.getAvailableIDs(); 61:for (int i = 0; i < ids.length; i++) 62:if (timeZoneIDmatch(ids[i], city)) 63:return TimeZone.getTimeZone(ids[i]); 64:return null; 65: } 66: 67: /** 68: Checks whether a time zone ID matches a city 69: @param id the time zone ID (e.g. "America/Los_Angeles") 70: @param aCity the city to match (e.g. "Los Angeles") 71: @return true if the ID and city match 72: */ 73:private static boolean timeZoneIDmatch(String id, // String city) 74: { Continued
File timezone/WEB-INF/classes/ bigjava/TimeZoneBean.java 75: String idCity = id.substring(id.indexOf('/') + 1); 76:return idCity.replace('_', ' ').equals(city); 77: } 78: 79:private DateFormat timeFormatter; 80:private String city; 81:private TimeZone zone; 82:}
File timezone/WEB-INF/faces-config.xml 01:<?xml version="1.0"?> 02: 03:<!DOCTYPE faces-config PUBLIC 04: "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" 05: "http://java.sun.com/dtd/web-facesconfig_1_0.dtd"> 06: 07:<faces-config> 08: <managed-bean> 09: <managed-bean-name>zone</managed-bean-name> 10: <managed-bean-class>bigjava.TimeZoneBean< /managed-bean-class> 11: <managed-bean-scope>session</managed-bean-scope> 12: <managed-property> 13: <property-name>city</property-name> 14: <value>Los Angeles</value> 15: </managed-property> 16: </managed-bean> 17:</faces-config>
File timezone/index.jsp 01:<html> 02: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 03: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 04: 05: <f:view> 06: <head> 07: <title>The timezone application</title> 08: </head> 09: <body> 10: <h:form> 11: <p> 12: The current date and time in 13: <h:outputText value="#{zone.city}"/> 14: is: 15: <h:outputText value="#{zone.time}"/> 16: </p> 17: <p> Continued