Chapter 27 JavaServer Pages and Servlets. Chapter Goals To implement dynamic web pages with JavaServer Faces (JSF) technology To learn the syntactical.

Slides:



Advertisements
Similar presentations
Chapter 25 JavaServer Pages and Servlets. CHAPTER GOALS To implement dynamic web pages with JavaServer Pages technology To learn the syntactical elements.
Advertisements

 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
Web applications using JavaServer Faces (JSF) A brief introduction 1JavaServer Faces (JSF)
JBoss Seam: Contextual Components Jason Bechtel
Internet Technologies 1 Master of Information System Management Java Server Faces Model/View/Controller Design Pattern for Web Development Slides.
JavaServer Faces. Objectives To implement dynamic web pages with JavaServer Faces (JSF) technology To learn the syntactical elements of JavaServer Faces.
Chapter 12: ADO.NET and ASP.NET Programming with Microsoft Visual Basic.NET, Second Edition.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 3-1 of…
Tomcat Configuration A Very, Very, Very Brief Overview.
ECE356 – Database Systems Lab 1 – Building a Web Project with NetBeans Tiuley Alguindigue Lab Instructor – University of Waterloo, E & CE Dept. Fall 2013.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
UNIT-V The MVC architecture and Struts Framework.
CST JavaScript Validating Form Data with JavaScript.
Chapter 9 Collecting Data with Forms. A form on a web page consists of form objects such as text boxes or radio buttons into which users type information.
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
11. Java-Based Web: JSP, JSF. 2 Motto: Rule 1: Our client is always right Rule 2: If you think our client is wrong, see Rule 1. - Anonymous.
CSCI 6962: Server-side Design and Programming Course Introduction and Overview.
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
1 Introduction to JavaServerFaces & MyFaces Anudeep Jassal.
CSCI 6962: Server-side Design and Programming Support Classes and Shopping Carts.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
JDeveloper 10g and JavaServer Faces: High-Performance UIs on the Web Avrom Roy-Faderman Senior Programmer May, 2006.
JavaServer Faces Jeff Schmitt October 5, Introduction to JSF Presents a standard framework for building presentation tiers for web applications.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
1 Lecture 24 George Koutsogiannakis Spring 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
CSCI 6962: Server-side Design and Programming Introduction to Java Server Faces.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
Web applications using JavaServer Faces (JSF) A brief introduction 1JavaServer Faces (JSF)
CSCI 6962: Server-side Design and Programming Java Server Faces Components and Tags.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Mark Dixon 1 12 – Java Beans. Mark Dixon 2 Session Aims & Objectives Aims –To cover the use of Java Beans Objectives, by end of this week’s sessions,
Struts J2EE web application framework “ Model 2 ” Model View Controller Controller Servlet Key features XML metadata Struts taglib Simplified form validation.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
J2EE Overview Web Programming CSCI J2EE multi-tier architecture Servlet: Java class loaded into Web server JSP page: enhanced HTML page that is.
Chapter 8 Collecting Data with Forms. Chapter 8 Lessons Introduction 1.Plan and create a form 2.Edit and format a form 3.Work with form objects 4.Test.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Introduction to HTML Part 3 Chapter 2. Learning Outcomes Identify how to design frames. Explain frames’ attributes. Describe the method on designing forms.
JAVA SERVER FACES ADITI RAJORIYA UNI – ar2630. POINTS TO BE DISSCUSED WHAT IS JSF? WHY JSF? ARCHITECTURE JSF VERSIONS UI COMPONENTS JSF STRUCTURE AND.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 41 JavaServer Face.
CSCI 6962: Server-side Design and Programming JSF DataTables and Shopping Carts.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
Chapter 5 Introduction To Form Builder. Lesson A Objectives  Display Forms Builder forms in a Web browser  Use a data block form to view, insert, update,
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml …
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
JavaServer Faces framework Craig McClanahan is presented that created Struts web framework and based on experience gathered designed JavaServer.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
1 Chapter 27 JavaServer Page. 2 Objectives F To know what is a JSP page is processed (§27.2). F To comprehend how a JSP page is processed (§27.3). F To.
Internet & World Wide Web How to Program, 5/e Copyright © Pearson, Inc All Rights Reserved.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
Lecture JAVA SERVLETS & JAVA SERVER PAGES François Major Université de Montréal
Chapter 26 – Web Applications. Chapter Goals To understand the web application concept To learn the syntactical elements of the JavaServer Faces web application.
Navigation Mimi Opkins CECS 493 Fall Static Navigation  In a simple web application, navigation is static. That is, clicking a particular button.
Chapter 26 – Web Applications
Web Development Using ASP .NET
Presentation transcript:

Chapter 27 JavaServer Pages and Servlets

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 Page title Page contents Each JSF page has the following structure:

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: 02: 03: 04: 05: 06: 07: The datetime application 08: 09: 10: 11: Number of milliseconds since January 1, 1970: 12: 13: 14: 15: 16: 17:

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: 02: 03: <!DOCTYPE faces-config PUBLIC 04: "-//Sun Microsystems, Inc. //DTD JavaServer Faces Config 1.0//EN" 05: " 06: 07: 08: 09: dateTime 10: java.util.Date 11: request 12: 13:

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 1.Make a subdirectory with the name of your web application in the webapps directory of your Tomcat installation or 2.Place the index.jsp file into that directory /usr/local/jakarta-tomcat/webapps/datetime Continued c:\Tomcat\webapps\datetime

Steps for Deploying a JSF Application 3.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 4.Place faces-config.xml into the WEB-INF subdirectory 5.Place your Java classes (if any) inside WEB-INF/classes 6.Place the file web.xml inside the WEB-INF subdirectory 7.Start the web server 8.Point your browser to

The Directory Structure of the datetime Application 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: 02: 03: <!DOCTYPE web-app PUBLIC 04: "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 05: " 06: 07: 08: 09: Faces Servlet 10: javax.faces.webapp.FacesServlet 11: 1 12: 13: 14: 15: Faces Servlet 16: *.faces 17: 18:

Self Check 1.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.) 2.Does a Swing program automatically separate presentation and business logic?

Answers 1.Place an image file, say clock.gif, into the datetime directory, and add a tag to the index.jsp file. 2.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: creditCard and 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 Continued user bigjava.UserBean session

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  first calls getCreditCard  When the user submits the form, the setCreditCard is called to store the edited property value

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. 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. 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. 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 aCity the city for which to find the time zone 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 id the time zone ID (e.g. "America/Los_Angeles") aCity the city to match (e.g. "Los Angeles") 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: 02: 03: <!DOCTYPE faces-config PUBLIC 04: "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" 05: " 06: 07: 08: 09: zone 10: bigjava.TimeZoneBean< /managed-bean-class> 11: session 12: 13: city 14: Los Angeles 15: 16: 17:

File timezone/index.jsp 01: 02: 03: 04: 05: 06: 07: The timezone application 08: 09: 10: 11: 12: The current date and time in 13: 14: is: 15: 16: 17: Continued

File timezone/index.jsp 18: Set time zone: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28:

The Directory Structure of the timezone Application Figure 7: The Directory Structure of the timezone Application

Self Check 3.Is the Random class a Java bean? 4.What work does the setCity method of the TimeZoneBean do besides setting the city instance field? 5.When you start the timezone application for the first time, why does the input field contain the string "Los Angeles"?

Answers 3.Technically, yes. It has a default constructor. However, it has no methods whose name start with get or set, so it exposes no properties. 4.It sets the zone instance field to match the time zone of the city. 5.When the zone bean was constructed, its city property was set to "Los Angeles". When the input field is rendered, its default value is the current value of the city property.

Session State and Cookies Figure 8: Viewing the Cookies in a Browser

JSF Components Each component has a value attribute to connect the component value with a bean property h:inputTextArea has attributes to specify the rows and columns Continued

JSF Components Radio button and checkbox groups allow you to specify horizontal or vertical layout:

JSF Components: Button Groups and Menus Require two properties:  the collection of possible choices  the actual choice The value attribute specifies the actual choice to be displayed The collection of possible choices is defined by a nested f:selectItems tag Continued

JSF Components: Button Groups and Menus monthChoices must have a type that can describe a list of choices  For example, Map  The keys of the map are the labels  The corresponding map values are the label values

Example: Using a Map to Describe a List of Choices To create the list of choices: Continued public class CreditCardBean {... public Map getMonthChoices() { Map choices = new LinkedHashMap (); choices.put("January", 1); choices.put("February", 2);... return choices; } }

Example: Using a Map to Describe a List of Choices The type of the value property of the component must match the type of the map value  For example, creditCard.expirationMonth must be an integer If multiple selections are allowed, the type of the value property must be a list or array of matching types

Common JSF Components

Self Check 6.Which JSF components can be used to give a user a choice between "AM/PM" and "military" time? 7.How would you supply a set of choices for a credit card expiration year to a h:selectOneMenu component?

Answers 6. h:selectOneRadio, h:selectOneMenu, or h:selectOneCheckbox

Answers 7.You would need a bean with a property such as the following: Then supply a tag public Map getYearChoices() { Map choices = new TreeMap (); choices.put("2003", 2003); choices.put("2004", 2004);... return choices; }

Navigation Between Pages Consider an enhancement of our timezone program We start with a page that prompts the user to enter the name of a city When the user clicks " Submit " a new page appears Continued

Navigation Between Pages Next page is either the page with the time display or an error page if no time zone is available The JSF container needs to determine which page to show next

Navigating Between Pages Figure 9: Navigating Between Pages

Navigation Between Pages Each button has an outcome, a string used to look up the next page Generally, next page may depend on the result of some computation We need different outcomes depending on the city entered Continued

Navigation Between Pages Specify a method binding as the action attribute: A method binding consists of the name of a bean and the name of a method

Navigation Between Pages When the form is submitted, the JSF engine calls zone.addCity() public class TimeZoneBean {... public String addCity() { if (zone == null) return "unavailable"; // Add the city... return "available"; } Continued

Navigation Between Pages If next page doesn't depend on a computation, you set the action attribute of the button to a fixed outcome string

Navigation Between Pages available /next.jsp unavailable /error.jsp back /index.jsp... faces-config.xml contains a navigation rule that maps outcome strings to pages: Continued

Navigation Between Pages Current page is redisplayed when  The button has no action attribute, or  The action outcome is not listed in the navigation rules

Self Check 8.What tag would you need to add to error.jsp so that the user can click on a button labeled "Help" and see help.jsp ? What other changes do you need to make to the web application? 9.Which page would be displayed if the addCity method returned null ?

Answers 8.Add the tag to error.jsp, and add a navigation rule to faces-config.xml: 9.The current page would be redisplayed. help /help.jsp

A Three-Tier Application A three-tier application has separate tiers for presentation, business logic, and data storage  The presentation tier: the web browser  The "business logic" tier: the JSF container, the JSF pages, and the JavaBeans  The storage tier: the database

Three-Tier Architecture Figure 10: Three-Tier Architecture

Two-Tier Client-Server Architecture Figure 10: Two-Tier Client-Server Architecture

A Three-Tier Application If business logic changes  In a two-tier application, new client program must be distributed over all desktops  In a three-tier application, server code is updated, while presentation tier remains unchanged Simpler to manage

A Three-Tier Application We will have a single database table, CityZone, with city and time zone names If the TimeZoneBean can't find the city among the standard time zone IDs, it makes a query: If there is a matching entry in the database, that time zone is returned SELECT Zone FROM CityZone WHERE City = the requested city

File multizone/misc/CityZone.sql\ 1: CREATE TABLE CityZone (City TEXT, Zone TEXT) 2: INSERT INTO CityZone VALUES ('San Francisco', 'America/Los Angeles') 3: INSERT INTO CityZone VALUES ('Kaoshiung', 'Asia/Taipei') 4: SELECT * FROM CityZone

The cityZone Table Figure 12: The cityZone Table

A Three-Tier Application To query the database, the bean needs a Connection object With Tomcat, specify the database configuration in conf/server.xml  Locate the element  Immediately after, add the configuration information found on the next slide  You need to place the JDBC driver file into common/lib  Restart server after changing the configuration file

A Three-Tier Application <Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource"/> factory org.apache.commons.dbcp. BasicDataSourceFactory driverClassName driver class url database URL Continued

A Three-Tier Application username database user name password database user password

A Three-Tier Application To obtain a database connection, first look up the data source that was configured in the JSF container: Continued InitialContext ctx = new InitialContext(); DataSource source = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb"); Connection conn = source.getConnection(); try { Use the connection } finally { conn.close(); }

A Three-Tier Application JSF containers such as Tomcat manage a pool of database connections  Pooling avoids the overhead of creating new database connections  Pooling is completely automatic

A Three-Tier Application Enhanced TimeZoneBean so that it manages a list of cities Can add cities to the list and remove a selected city Continued

A Three-Tier Application Figure 13: The multizone Application Shows a List of Cities

The Directory Structure of the multizone Application Figure 14: The Directory Structure of the multizone Application

File multizone/index.jsp 01: 02: 03: 04: 05: 06: 07: The multizone application 08: 09: 10: 11: 12: Enter city: 13: 14: 15: Continued

File multizone/index.jsp 16: <h:commandButton value="Submit" action="#{zone.addCity}"/> 17: 18: 19: 20: 21:

File multizone/next.jsp 01: 02: 03: 04: 05: 06: 07: The multizone application 08: 09: 10: 11: 12: <h:selectOneRadio value="#{zone.cityToRemove}" 13: layout="pageDirection"> 14: <f:selectItems value= "#{zone.citiesAndTimes}"/> 15: Continued

File multizone/next.jsp 16: 17: 18: <h:commandButton value= "Remove selected" action ="#{zone.removeCity}"/> 19: <h:commandButton value= "Add another" action="back"/> 20: 21: 22: 23: 24:

File multizone/error.jsp 01: 02: 03: 04: 05: 06: 07: The multizone application 08: 09: 10: 11: 12: Sorry, no information is available for 13: 14: 15: Continued

File multizone/error.jsp 16: 17: 18: 19: 20: 21:

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 001: package bigjava; 002: 003: import java.sql.Connection; 004: import java.sql.PreparedStatement; 005: import java.sql.ResultSet; 006: import java.sql.SQLException; 007: import java.text.DateFormat; 008: import java.util.ArrayList; 009: import java.util.Date; 010: import java.util.Map; 011: import java.util.TimeZone; 012: import java.util.TreeMap; 013: import java.util.logging.Logger; 014: import javax.naming.InitialContext; 015: import javax.naming.NamingException; 016: import javax.sql.DataSource; Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 017: 018: /** 019: This bean formats the local time of day for a given date 020: and city. 021: */ 022: public class TimeZoneBean 023: { 024: /** 025: Initializes the formatter. 026: */ 027: public TimeZoneBean() 028: { 029: timeFormatter = DateFormat.getTimeInstance(); 030: cities = new ArrayList (); 031: } 032: Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 033: /** 034: Setter for city property. aCity the city to add to the list of cities 036: */ 037: public void setCity(String aCity) 038: { 039: city = aCity; 040: zone = getTimeZone(city); 041: } 042: 043: /** 044: Getter for city property. the city to add to the list of cities 046: */ 047: public String getCity() 048: { Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 049: return city; 050: } 051: 052: /** 053: Setter for the cityToRemove property aCity the city to remove 055: */ 056: public void setCityToRemove(String aCity) 057: { 058: cityToRemove = aCity; 059: } 060: 061: /** 062: Getter for the cityToRemove property. the empty string 064: */ Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 065: public String getCityToRemove() 066: { 067: return cityToRemove; 068: } 069: 070: /** 071: Read-only citiesAndTimes property. a map containing the cities and // formatted times 073: */ 074: public Map getCitiesAndTimes() 075: { 076: Date time = new Date(); 077: Map result = new TreeMap (); 078: for (int i = 0; i < cities.size(); i++) 079: { Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 080: String city = cities.get(i); 081: String label = city + ": "; 082: TimeZone zone = getTimeZone(city); 083: if (zone != null) 084: { 085: timeFormatter.setTimeZone(zone); 086: String timeString = timeFormatter.format(time); 087: label = label + timeString; 088: } 089: else 090: label = label + "unavailable"; 091: result.put(label, city); 092: } 093: 094: return result; 095: } 096: Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 097: /** 098: Action for adding a city. "available" if time zone information is // available for the city, 100: "unavailable" otherwise 101: */ 102: public String addCity() 103: { 104: if (zone == null) return "unavailable"; 105: cities.add(city); 106: cityToRemove = city; 107: city = ""; 108: return "available"; 109: } 110: Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 111: /** 112: Action for removing a city. null if there are more cities to remove, // "back" otherwise 114: */ 115: public String removeCity() 116: { 117: cities.remove(cityToRemove); 118: if (cities.size() > 0) return null; 119: else return "back"; 120: } 121: 122: /** 123: Looks up the time zone for a city aCity the city for which to find the time zone the time zone or null if no match is found 126: */ Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 127: private static TimeZone getTimeZone(String city) 128: { 129: String[] ids = TimeZone.getAvailableIDs(); 130: for (int i = 0; i < ids.length; i++) 131: if (timeZoneIDmatch(ids[i], city)) 132: return TimeZone.getTimeZone(ids[i]); 133: try 134: { 135: String id = getZoneNameFromDB(city); 136: if (id != null) 137: return TimeZone.getTimeZone(id); 138: } 139: catch (Exception exception) 140: { 141: Logger.global.info("Caught in TimeZone.getTimeZone: " + exception); 142: } Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 143: return null; 144: } 145: 146: private static String getZoneNameFromDB(String city) 147: throws NamingException, SQLException 148: { 149: InitialContext ctx = new InitialContext(); 150: DataSource source 151: = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb"); 152: Connection conn = source.getConnection(); 153: try 154: { 155: PreparedStatement stat = conn.prepareStatement( 156: "SELECT Zone FROM CityZone WHERE City=?"); 157: stat.setString(1, city); 158: ResultSet result = stat.executeQuery(); Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 159: if (result.next()) 160: return result.getString(1); 161: else 162: return null; 163: } 164: finally 165: { 166: conn.close(); 167: } 168: } 169: 170: /** 171: Checks whether a time zone ID matches a city id the time zone ID (e.g. "America/Los_Angeles") aCity the city to match (e.g. "Los Angeles") true if the ID and city match 175: */ Continued

File multizone/WEB-INF/classes/ bigjava/TimeZoneBean.java 176: private static boolean timeZoneIDmatch(String id, String city) 177: { 178: String idCity = id.substring(id.indexOf('/') + 1); 179: return idCity.replace('_', ' ').equals(city); 180: } 181: 182: private DateFormat timeFormatter; 183: private ArrayList cities; 184: private String city; 185: private TimeZone zone; 186: private String cityToRemove; 187: }

File multizone/WEB-INF/faces- config.xml 01: 02: 03: <!DOCTYPE faces-config PUBLIC 04: "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" 05: " 06: 07: 08: 09: 10: available 11: /next.jsp 12: 13: 14: unavailable 15: /error.jsp 16: Continued

File multizone/WEB-INF/faces- config.xml 17: 18: back 19: /index.jsp 20: 21: 22: 23: zone 24: bigjava.TimeZoneBean 25: session 26: 27:

Self Check 10.Why don't we just keep a database connection as an instance field in the TimeZoneBean ? 11.Why does the removeCity method of the TimeZoneBean return null or "back", depending on the size of the cities field?

Answers 10.Then the database connection would be kept open for the entire session. 11.As long as there are cities, the next.jsp page is redisplayed. If all cities are removed, it is pointless to display the next.jsp page, so the application navigates to the index.jsp page.