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

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
JSP and Servelets.
JSP and web applications
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
JLab Lattice Portal – Data Grid Web Service Ying Chen, Chip Watson Thomas Jefferson National Accelerator Facility.
Exercises of the Tutorial on Advanced Web Programming Authors: Miroslava Mitrovic Dragan Milicev Nino.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Java Server Pages (JSP)
Java Servlets Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
JavaServer Faces. Objectives To implement dynamic web pages with JavaServer Faces (JSF) technology To learn the syntactical elements of JavaServer Faces.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
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.
JSP Java Server Pages Softsmith Infotech.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
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.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
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.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
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,
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaServer Page.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
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.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Lecture JAVA SERVLETS & JAVA SERVER PAGES François Major Université de Montréal
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
Scripted Page Web App Development (Java Server Pages)
Chapter 26 Servlets.
Presentation transcript:

Chapter 25 JavaServer Pages and Servlets

CHAPTER GOALS To implement dynamic web pages with JavaServer Pages technology To learn the syntactical elements of JavaServer Pages To structure a web application as a sequence of JavaServer Pages To understand the relationship between JavaServer Pages and servlets

Dynamic Web Content You can use JavaServer Pages (JSP) to implement dynamic web pages To use JSP's you need a web server that is integrated with a JSP container Apache Tomcat server is free

Dynamic Web Content A JavaServer Pages (JSP) page contains HTML tags and Java instructions The Java instructions are executed each time the page is served to the browser An instruction to insert the current date and time into a web page

File date.jsp 01: 02: 03: Date JSP 04: 05: 06: Date JSP 07: The current time is: 08: 09: 10: 11: 12:

Executing the Date Page

To Deploy the Date Page 1. Type the JSP file into a text editor 2. Place the file into a web application directory of your JSP engine 3. If you use Tomcat, create a subdirectory for the JSP file c:\jakarta-tomcat\webapps\bigjava 4. Place the date.jsp file into that directory 5. Start the web server 6. Point your browser to localhost:8080/bigjava/date.jsp

Dynamic Web Content The JSP container reads the requested JSP page and transforms it into an HTML page Regular HTML tags are left unchanged JSP tags ( ) are processed Expressions enclosed in JSP tags are evaluated and converted to a string using toString method

Dynamic Web Content The string is inserted into the HTML page The resulting document contains only HTML The web server sends the document to the browser

The JSP Container Rewrites the Requested Page

Encapsulating Computations in JavaBeans Most professional web pages need input from two different experts o A programmer who understands how to compute the results the page will display o A graphics designer who determines how to display the results It is best to keep the Java code and the HTML tags separate Any nontrivial computation should be carried out in a separate Java class You connect one or more JavaBeans to a JSP page

Encapsulating Computations in JavaBeans A JavaBean is a Java class It must have a default constructor A JavaBean exposes its properties through get and set methods Properties are accessed and modified by methods that follow a naming convention

Encapsulating Computations in JavaBeans If the property name is propertyName and the type is Type o accessor method Type getPropertyName() o mutator method void setpropertyName(Type newValue) A boolean property uses a different convention boolean isPropertyName() void setPropertyName(boolean newValue) By convention the name of the bean ends in Bean Do not make any assumptions about the internal representation of the data

Encapsulating Computations in JavaBeans A JSP page gives you access to a JavaBean's properties without having to write Java code. To use a bean in a JSP page, use the jsp:useBean directive Give a name to the object and specify the class name of the bean This directive invokes the default constructor of the PersonBean class It makes an object with name user

Encapsulating Computations in JavaBeans To set a property in the bean, use the setProperty directive To get a property in the bean, use the getProperty directive This returns a string that becomes part of the HTML page

Encapsulating Computations in JavaBeans We want to display just the current time, not the whole date Get the time with the getTimeInstance method of the DateFormat class Put this code in a bean class

File TimeFormatterBean.Java 01: import java.text.DateFormat; 02: import java.util.Date; 03: 04: /** 05: This bean formats the time of day from a given date. 06: */ 07: public class TimeFormatterBean 08: { 09: /** 10: Initializes the formatter. 11: */ 12: public TimeFormatterBean() 13: { 14: timeFormatter = DateFormat.getTimeInstance(); 15: } 16: 17: /** 18: Write-only date property. aDate the date to be formatted.

20: */ 21: public void setDate(Date aDate) 22: { 23: theDate = aDate; 24: } 25: 26: /** 27: Read-only time property. the formatted time 29: */ 30: public String getTime() 31: { 32: String timeString = timeFormatter.format(theDate); 33: return timeString; 34: } 35: 36: private DateFormat timeFormatter; 37: private Date theDate; 38: }

File time.jsp 01: 02: "/> 03: 04: 05: Time JSP 06: 07: 08: Time JSP 09: The current time is: 10: 11: 12: 13: 14:

Encapsulating Computations in JavaBeans It is a good idea to put the bean directive at the beginning of the JSP file, before the HTML Both time.jsp and TimeFormatterBean must be deployed to the proper directories time.jsp into c:\Jakarta-tomcat\webapps\bigjava TimeFormatterBean into c:\Jakarta-tomcat\webapps\bigjava\WEB-INF\classes You use JavaBeans to separate HTML presentation from Java computation

Handling Request Parameters Modify the JSP page to take as input the user's city and to return the time in that time zone The Java library contains a TimeZone class that knows about time zones A time zone is identified by a string such as o "America/Los_Angeles" o "Asia/Tokyo" The static method getAvailableIDs returns a string array containing all IDs The static getTimeZone method returns a TimeZone class for a given ID string String zoneID = "America/Los_Angeles"; TimeZone zone = TimeZone.getTimeZone(zoneID);

Handling Request Parameters The user will enter a city like Los Angeles Our time zone bean will check whether that string appears at the end of one of the time zone ID's The JSP page formats the current time in that time zone Or prints a message that the city name is not found

Handling Request Parameters We need an HTML form to get the user input The form will have a textfield and a button to submit the form to the JSP

File timezone.html 01: 02: 03: Time Zone Form 04: 05: 06: 07: City: 08: 09: 10: 11: 12: 13:

The HTML Form for Entering City Names

Handling Request Parameters When a browser submits a form, it sends the names and values of all form elements to the web server o The name is city o the value is the contents of the text field The action attribute of the form element specifies the URL of the server-side program that processes the form o In this case timezone.jsp In a JSP page, you can access the form data through the predefined request object The getParameter method of the ServletRequest class returns the value of the form element with a given name To get the city that the user typed o

Handling Request Parameters To set the city property in the TimeZoneBean /> A convenient shorthand

File timezone.jsp 01: 02: "/> 03: 04: 05: Time Zone JSP 06: 07: 08: Time Zone JSP 09: The current time in is: 10: 11: 12: 13:

File TimeZoneBean.java 01: import java.text.DateFormat; 02: import java.util.Date; 03: import java.util.TimeZone; 04: 05: /** 06: This bean formats the local time of day for a given date 07: and city. 08: */ 09: public class TimeZoneBean 10: { 11: /** 12: Initializes the formatter. 13: */ 14: public TimeZoneBean() 15: { 16: timeFormatter = DateFormat.getTimeInstance(); 17: }

18: 19: /** 20: Write-only date property. aDate the date to be formatted. 22: */ 23: public void setDate(Date aDate) 24: { 25: theDate = aDate; 26: } 27: 28: /** 29: Write-only city property. aCity the city for which to report the local time 31: */ 32: public void setCity(String aCity) 33: { 34: city = aCity; 35: } 36: 37: /**

38: Read-only available property. true if time zone information is available for 40: this city. 41: */ 42: public boolean isAvailable() 43: { 44: return getTimeZone(city) != null; 45: } 46: 47: /** 48: Read-only time property. the formatted time 50: */ 51: public String getTime() 52: { 53: TimeZone zone = getTimeZone(city); 54: if (zone == null) return "not available"; 55: timeFormatter.setTimeZone(zone); 56: String timeString = timeFormatter.format(theDate); 57: return timeString;

58: } 59: 60: /** 61: 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 64: */ 65: private static TimeZone getTimeZone(String city) 66: { 67: String[] ids = TimeZone.getAvailableIDs(); 68: for (int i = 0; i < ids.length; i++) 69: if (timeZoneIDmatch(ids[i], city)) 70: return TimeZone.getTimeZone(ids[i]); 71: return null; 72: } 73: 74: /** 75: 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 79: */ 80: private static boolean timeZoneIDmatch(String id, String city) 81: { 82: String idCity = id.substring(id.indexOf('/') + 1); 83: return idCity.replace('_', ' ').equals(city); 84: } 85: 86: private DateFormat timeFormatter; 87: private Date theDate; 88: private String city; 89: }

The Output of the Time Zone JSP Page previousprevious | start | nextstartnext previousprevious | start | nextstartnext

HTML Forms An HTML form contains user interface elements such as: o Text fields o Password fields o Text areas o Radio buttons o Check boxes o Selection lists o Submit buttons o Hidden fields

The HTML Form Elements

HTML Forms Most form elements have the syntax You should include a name attribute on every element except submit button You may include a value attribute with a default value

HTML Forms Text field Password Text area default text

HTML Forms Radio button Small Medium Large Extra large o Only one radio button can be checked at a time Check box Mushrooms Anchovies o More than one checkbox in a group can have the checked attribute set to "checked" o If both boxes are checked the browser sends the server toppings=mushrooms+toppings=anchovies

HTML Forms Selection list January February March April. December

Submit button Hidden field o The browser does not display a hidden field o It sends the name/value pairs in the field to the server when the form is submitted

HTML Forms Place all elements that belong to a form into a form element. An HTML form must specify the URL of the server program that processes the form data The action attribute contains the URL Set the method attribute to POST because it has no length limit

Session Tracking A session is a sequence of page requests from the same browser to the same web server To track a session in a sequence of JSP pages, use a bean with session scope The user requests the JSP page containing this directive for the first time oA new cart object is constructed The user returns to the same page or visits another page in the same application oThe cart object is still alive If the bean directive has no scope attribute oThe bean object has page scope oA new object is created every time the page is visited

Session Tracking Create a program that allows the user to keep adding cities and their time zones In the initial HTML form, the web application asks for the name of the first city The JSP page displays the first city and a form to enter another city The user can add as many cities as he likes All cities are stored in an object of the MultiZoneBean class

Session Tracking The bean object has session scope and so holds a list of all the cities Keep cities in a MultiZoneBean An instance is created for each session The setCity method adds a city to the bean object The new city is the value of the text field whose name is city

Asking for the First of Several Cities

Asking for the Next City

Display the Time in Multiple Locations

File multizone.html 01: 02: 03: Multiple Time Zone Form 04: 05: 06: <form action="multizone.jsp" 07: method="POST"> 08: First City: 09: 10: 11: 12: 13: 14:

File multizone.jsp 01: 02: "/> 03: 04: "/> 05: 06: 07: 08: Multiple Time Zone JSP 09: 10: 11: Current time lookup 12: 13: 14:

15: <form action="multizone.jsp" 16: method="POST"> 17: Next City: 18: 19: 20: 21: 22: 23:

File MultiZoneBean.java 01: import java.text.DateFormat; 02: import java.util.ArrayList; 03: import java.util.Date; 04: import java.util.TimeZone; 05: 06: /** 07: This bean formats the local times of day for a given date 08: and list of cities. 09: */ 10: public class MultiZoneBean 11: { 12: /** 13: Initializes the formatter and city list. 14: */ 15: public MultiZoneBean() 16: { 17: timeFormatter = DateFormat.getTimeInstance();

18: cities = new ArrayList(); 19: } 20: 21: /** 22: Write-only date property. aDate the date to be formatted. 24: */ 25: public void setDate(Date aDate) 26: { 27: theDate = aDate; 28: } 29: 30: /** 31: Write-only city property. aCity the city to add to the city list 33: */ 34: public void setCity(String aCity) 35: { 36: cities.add(aCity); 37: }

38: 39: /** 40: Read-only times property. a string containing the HTML code for an unnumbered 42: list of cities and local times 43: */ 44: public String getTimes() 45: { 46: StringBuffer buffer = new StringBuffer(); 47: for (int i = 0; i < cities.size(); i++) 48: { 49: String city = (String)cities.get(i); 50: 51: buffer.append(" "); 52: buffer.append(city); 53: buffer.append(": "); 54: 55: TimeZone zone = getTimeZone(city); 56: if (zone == null) 57: buffer.append("not available");

58: else 59: { 60: timeFormatter.setTimeZone(zone); 61: String timeString = timeFormatter.format(theDate); 62: buffer.append(timeString); 63: } 64: buffer.append(" "); 65: } 66: return buffer.toString(); 67: } 68: 69: /** 70: 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 73: */ 74: private static TimeZone getTimeZone(String city) 75: { 76: String[] ids = TimeZone.getAvailableIDs(); 77: for (int i = 0; i < ids.length; i++)

78: if (timeZoneIDmatch(ids[i], city)) 79: return TimeZone.getTimeZone(ids[i]); 80: return null; 81: } 82: 83: /** 84: 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 88: */ 89: private static boolean timeZoneIDmatch(String id, String city) 90: { 91: String idCity = id.substring(id.indexOf('/') + 1); 92: return idCity.replace('_', ' ').equals(city); 93: } 94: 95: private DateFormat timeFormatter; 96: private Date theDate; 97: private ArrayList cities; 98: }

Branching and Forwarding Pages A JSP page can forward a request to another page You can use forwarding to implement branches Post the query to a JSP page that checks the input but has no HTML output The page evaluates the input and uses the jsp:forward directive to select another page

Branching and Forwarding Pages The forward directive has the format It causes the JSP engine to load the page at the URL The request data of the current bean and beans with scope="request" are forwarded to new page Branch and forward page : <% if (some condition) { %> <% } else { %> <% } %>

Branching and Forwarding Pages We can use this technique to handle cities for which no time zone is known Start with the same HTML form Use the same html Except post the data to a non-visual JSP page This page then forwards the request to the proper page

File zonebranch.html 01: 02: 03: Time Zone Branch Form 04: 05: 06: 07: City: 08: 09: 10: 11: 12: 13:

File zonebranch.jsp 01: 02: "/> 03: 04: <% 05: if (zone.isAvailable()) 06: { 07: %> 08: 09: <% 10: } 11: else 12: { 13: %> 14: 15: <% 16: } 17: %>

File zoneresult.jsp 01: 02: 03: Time Zone Branch Result JSP 04: 05: 06: Time Zone Branch Result JSP 07: The current time in is: 08: 09: 10: 11:

File zoneerror.jsp 01: 02: 03: Time Zone Error JSP 04: 05: 06: Unfortunately, no information is available for 07:. Please enter 08: another city. 09: 10: 11: City: 12: 13: 14: 15: 16: 17:

A Three-Tier Application The presentation tier: the web browser The business logic tier: the JSP engine, JSP pages, and the JavaBean The storage tier: the database

A Three-Tier Application Database table CityZone ZoneDBBean consults this database to find the user requested city If not available, it looks through the ID's as MultiZoneBean did Use a DataSourceBean to manage the database connection

A Three-Tier Application Only one instance of DataSourceBean needed for all JSP pages that make up the web application Set its scope to "application" Store the database properties in the file web.xml in the WEB_INF subdirectory The JSP pages can access the information in web.xml Use the getInitParameter method of the predefined application object

A Three-Tier Application Retrieve the database information from web.xml and initialize the database Any directives you place as child elements of the jsp:useBean element are executed only once ZoneDBBean makes a database query to find the requested city

File zonedb.html 01: 02: 03: Time Zone Database Form 04: 05: 06: 07: City: 08: 09: 10: 11: 12: 13:

File zonedb.jsp 01: 02: <jsp:setProperty name="db" property="driver" 03: value=' '/> 04: <jsp:setProperty name="db" property="url" 05: value=' '/> 06: <jsp:setProperty name="db" property="username" 07: value=' '/> 08: <jsp:setProperty name="db" property="password" 09: value=' '/> 10: 11: 12: 13: 14: "/> 15: "/> 16:

17: 18: 19: Zone Database JSP 20: 21: 22: Zone Database JSP 23: The current time in is: 24: 25: 26: 27:

File DataSourceBean.Java 01: import java.sql.DriverManager; 02: import java.sql.Connection; 03: import java.sql.SQLException; 04: 05: /** 06: A simple data source bean for getting database connections. 07: */ 08: public class DataSourceBean 09: { 10: /** 11: Write-only driver property. driver the database driver name 13: */ 14: public void setDriver(String driver) 15: throws ClassNotFoundException 16: { 17: Class.forName(driver);

18: } 19: 20: /** 21: Write-only url property. aUrl the JDBC URL 23: */ 24: public void setUrl(String aUrl) 25: { 26: url = aUrl; 27: } 28: 29: /** 30: Write-only username property. aUsername the database user name 32: */ 33: public void setUsername(String aUsername) 34: { 35: username = aUsername; 36: } 37:

38: /** 39: Write-only password property. aUsername the database user's password 41: */ 42: public void setPassword(String aPassword) 43: { 44: password = aPassword; 45: } 46: 47: /** 48: Gets a connection to the database. the database connection 50: */ 51: public static Connection getConnection() 52: throws SQLException 53: { 54: return 55: DriverManager.getConnection(url, username, password); 56: } 57:

58: private static String url; 59: private static String username; 60: private static String password; 61: }

File ZoneDBBean.Java 001: import java.text.DateFormat; 002: import java.util.Date; 003: import java.util.TimeZone; 004: import java.sql.Connection; 005: import java.sql.Statement; 006: import java.sql.ResultSet; 007: import java.sql.SQLException; 008: 009: /** 010: This bean formats the local time of day for a given date 011: and city, consulting a database in addition to the standard 012: time zone ID list. 013: */ 014: public class ZoneDBBean 015: { 016: /** 017: Initializes the formatter.

018: */ 019: public ZoneDBBean() 020: { 021: timeFormatter = DateFormat.getTimeInstance(); 022: } 023: 024: /** 025: The city property. the city for which to report the local time 027: */ 028: public String getCity() 029: { 030: return city; 031: } 032: 033: /** 034: The city property. aCity the city for which to report the local time 036: */ 037: public void setCity(String aCity)

038: { 039: city = aCity; 040: } 041: 042: /** 043: Write-only date property. aDate the date to be formatted. 045: */ 046: public void setDate(Date aDate) 047: { 048: theDate = aDate; 049: } 050: 051: /** 052: Read-only time property. the formatted time 054: */ 055: public String getTime() throws SQLException 056: { 057: TimeZone zone = null;

058: zone = getTimeZoneDB(); 059: if (zone == null) // not found in database 060: zone = getTimeZone(city); 061: if (zone == null) return "not available"; 062: timeFormatter.setTimeZone(zone); 063: return timeFormatter.format(theDate); 064: } 065: 066: /** 067: Looks up the time zone for a city in the database and 068: the list of time zone IDs. aCity the city for which to find the time zone the time zone or null if no match is found 071: */ 072: private TimeZone getTimeZoneDB() throws SQLException 073: { 074: Connection conn = null; 075: try 076: { 077: conn = DataSourceBean.getConnection();

078: Statement stat = conn.createStatement(); 079: String query = "SELECT Zone FROM CityZone" 080: + " WHERE City = '" + city + "'"; 081: ResultSet result = stat.executeQuery(query); 082: if (result.next()) 083: return TimeZone.getTimeZone(result.getString(1)); 084: else 085: return null; 086: } 087: finally 088: { 089: if (conn != null) conn.close(); 090: } 091: } 092: 093: /** 094: Looks up the time zone for a city in the list of time 095: zone IDs aCity the city for which to find the time zone the time zone or null if no match is found

098: */ 099: private static TimeZone getTimeZone(String city) 100: { 101: String[] ids = TimeZone.getAvailableIDs(); 102: for (int i = 0; i < ids.length; i++) 103: if (timeZoneIDmatch(ids[i], city)) 104: return TimeZone.getTimeZone(ids[i]); 105: return null; 106: } 107: 108: /** 109: 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 113: */ 114: private static boolean timeZoneIDmatch(String id, String city) 115: { 116: String idCity = id.substring(id.indexOf('/') + 1); 117: return idCity.replace('_', ' ').equals(city);

118: } 119: 120: private Date theDate; 121: private DateFormat timeFormatter; 122: private String city; 123: }

Servlets Servlets are an alternative to JSPs for building web applications JSP pages are actually translated into Servlets A servlet is a Java program o It carries out computations o And can emit data that is returned to the browser

Servlets A servlet is a class that extends HTTPServlet class To handle GET requests, a servlet implements doGet void doGet( HttpServletRequest request, HttpServletResponse response) To handle POST requests, a servlet implements doPost void doPost( HttpServletRequest request, HttpServletResponse response)

Servlets This example does not receive any request information The servlet o Obtains the current time o Creates HTML document containing the information o Sends the page back to the browser

Servlets The request parameter contains information about the request Not used in this example The response parameter lets you specify what to send back to the browser

Servlets To send an HTML document back to the browser Set the content type of the response to HTML response.setContentType("text/html"); Get a print writer to collect the document to be sent PrintWriter out = response.getWriter(); Print the HTML document to the print writer Close the print writer

File DateServlet.Java 01: import java.io.PrintWriter; 02: import java.io.IOException; 03: import java.util.Date; 04: import javax.servlet.ServletException; 05: import javax.servlet.http.HttpServlet; 06: import javax.servlet.http.HttpServletRequest; 07: import javax.servlet.http.HttpServletResponse; 08: 09: /** 10: This servlet prints out the current date and time. 11: */ 12: public class DateServlet extends HttpServlet 13: { 14: public void doGet(HttpServletRequest request, 15: HttpServletResponse response) 16: throws ServletException, IOException 17: { 18: // get information 19: String now = new Date().toString();

20: 21: // set content type to HTML 22: response.setContentType("text/html"); 23: 24: // print formatted information 25: PrintWriter out = response.getWriter(); 26: 27: String title = "Date Servlet"; 28: out.println(" "); 29: out.println(title); 30: out.println(" "); 31: out.print(title); 32: out.println(" The current time is: "); 33: out.println(now); 34: out.println(" "); 35: 36: out.close(); 37: } 38: }

Servlets To deploy a servlet, you need to write a deployment descriptor The deployment descriptor gives the servlet a name The name may be different than the class name The deployment descriptor tells how to locate the servlet class The deployment descriptor tells which URL's map to the servlet

Servlets The deployment descriptor must be in the web.xml file The web.xml file goes in the WEB-INF subdirectory of the web application directory Put the class files into the classes subdirectory of the WEB-INF directory

Placement of Web Application Files

Servlets This second servlet lets the user supply a city name Use the request parameter of the doPost method to get the value Use the getParameter method of the request object

File zoneservlet.html 01: 02: 03: Time Zone Servlet Form 04: 05: 06: 07: City: 08: 09: 10: 11: 12: 13:

File TimeZoneServlet.Java 01: import java.io.PrintWriter; 02: import java.io.IOException; 03: import java.text.DateFormat; 04: import java.util.Date; 05: import java.util.TimeZone; 06: import javax.servlet.ServletException; 07: import javax.servlet.http.HttpServlet; 08: import javax.servlet.http.HttpServletRequest; 09: import javax.servlet.http.HttpServletResponse; 10: 11: /** 12: This servlet prints out the current local time. 13: The city name must be posted as value of the 14: "city" parameter. 15: */ 16: public class TimeZoneServlet extends HttpServlet 17: {

18: public void doPost(HttpServletRequest request, 19: HttpServletResponse response) 20: throws ServletException, IOException 21: { 22: // get information 23: 24: String cityName = request.getParameter("city"); 25: TimeZone zone = getTimeZone(cityName); 26: 27: // set content type to HTML 28: response.setContentType("text/html"); 29: 30: // print formatted information 31: PrintWriter out = response.getWriter(); 32: 33: String title = "Time Zone Servlet"; 34: out.println(" "); 35: out.println(title); 36: out.println(" "); 37: out.print(title);

38: out.println(" "); 39: 40: if (zone == null) 41: out.println("Sorry--unknown city"); 42: else 43: { 44: out.print("The current time in "); 45: out.print(cityName); 46: out.print(" is: "); 47: DateFormat formatter = DateFormat.getTimeInstance(); 48: formatter.setTimeZone(zone); 49: Date now = new Date(); 50: out.print(formatter.format(now)); 51: } 52: out.println(" "); 53: 54: out.close(); 55: } 56: 57: /**

58: 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 61: */ 62: private static TimeZone getTimeZone(String city) 63: { 64: String[] ids = TimeZone.getAvailableIDs(); 65: for (int i = 0; i < ids.length; i++) 66: if (timeZoneIDmatch(ids[i], city)) 67: return TimeZone.getTimeZone(ids[i]); 68: return null; 69: } 70: 71: /** 72: 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 76: */ 77: private static boolean timeZoneIDmatch(String id, String city)

78: { 79: String idCity = id.substring(id.indexOf('/') + 1); 80: return idCity.replace('_', ' ').equals(city); 81: } 82: }

Compilation of JSP Pages The JSP container translates the JSP pages into servlets This happens when the page is first requested Also whenever the page has changed Bean directives translate into Java code