Title: JavaServer Pages and Servlets
1Chapter 25
- JavaServer Pages and Servlets
2CHAPTER 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
3Dynamic 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
4Dynamic 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
-
5File date.jsp
- 01
- 02
- 03 Date JSP
- 04
- 05
- 06 Date JSP
- 07 The current time is
- 08
- 09
- 10
- 11
- 12
6Executing the Date Page
7To 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
- localhost8080/bigjava/date.jsp
8Dynamic 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
9Dynamic 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
10The JSP Container Rewrites the Requested Page
11Encapsulating Computations in JavaBeans
- Most professional web pages need input from
two different experts
- A programmer who understands how to compute
the results the page will display
- 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
12Encapsulating 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
13Encapsulating Computations in JavaBeans
- If the property name is propertyName and the
type is Type
- accessor method
- Type getPropertyName()
- 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
14Encapsulating 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
jspuseBean 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
15Encapsulating Computations in JavaBeans
- To set a property in the bean, use the
setProperty directive
- value"true"/
- To get a property in the bean, use the
getProperty directive
-
- This returns a string that becomes part of the
HTML page
16Encapsulating 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
17- 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 TimeFormatter
Bean() 13 14 timeFormatter DateFo
rmat.getTimeInstance() 15 16 17 /
18 Write-only date property. 19
_at_param aDate the date to be formatted.
1820 / 21 public void setDate(Date aDate)
22 23 theDate aDate 24
25 26 / 27 Read-only time prop
erty. 28 _at_return the formatted time 29
/ 30 public String getTime() 31 32
String timeString timeFormatter.format(t
heDate) 33 return timeString 34
35 36 private DateFormat timeFormatter 37
private Date theDate 38
1901 class"TimeFormatterBean"/ 02
name"formatter" property"date" value"
java.util.Date() "/ 03 04
05 Time JSP 06
07 08 Time JSP 09
The current time is
10
property"time"/ 11 12
13 14
20Encapsulating 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
21Handling 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
- "America/Los_Angeles"
- "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)
22Handling 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
23Handling 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
2401 02 03 Time
Zone Form 04 05
06 07
City 08
t" name"city"/ 09
bmit" value"Get Time"/ 10 11
12 13
25The HTML Form for Entering City Names
26Handling Request Parameters
- When a browser submits a form, it sends the
names and values of all form elements to the web
server
- The name is city
- 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
- 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
-
27Handling Request Parameters
- To set the city property in the TimeZoneBean
value" /
- A convenient shorthand
- param"city"/
2801
02
value""/
03
param"city"/ 04 05
itleTime Zone JSP 06 07
08 Time Zone JSP 09
The current time in
("city") is 10
e"zone" property"time"/ 11 12
13
29File 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.getTimeInstan
ce()
- 17
30- 18
- 19 /
- 20 Write-only date property.
- 21 _at_param 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.
- 30 _at_param aCity the city for which to
report the local time
- 31 /
- 32 public void setCity(String aCity)
- 33
- 34 city aCity
- 35
- 36
31- 38 Read-only available property.
- 39 _at_return 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.
- 49 _at_return 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)
32- 58
- 59
- 60 /
- 61 Looks up the time zone for a city
- 62 _at_param aCity the city for which to find
the time zone
- 63 _at_return 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
- 69 if (timeZoneIDmatch(idsi, city))
- 70 return TimeZone.getTimeZone(idsi
)
- 71 return null
- 72
- 73
- 74 /
- 75 Checks whether a time zone ID matches a
city
- 76 _at_param id the time zone ID (e.g.
"America/Los_Angeles")
33- 78 _at_return true if the ID and city match
- 79 /
- 80 private static boolean timeZoneIDmatch(Stri
ng 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
34The Output of the Time Zone JSP Page
previous start next
previous start next
35HTML 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
36The HTML Form Elements
37HTML 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
38HTML Forms
- Text field
- value"USA" size"16" maxlength"16" /
- Password
- size"16" maxlength"16" /
- Text area
-
default text
-
39HTML Forms
- Radio button
- value"S"/Small
- value"M"/Medium
- checked"checked"/Large
- value"XL"/Extra large
- Only one radio button can be checked at a
time
- Check box
- value"mushrooms" checked"checked"/Mushrooms
- value"anchovies" /Anchovies
- More than one checkbox in a group can have
the checked attribute set to "checked"
- If both boxes are checked the browser sends
the server toppingsmushroomstoppingsanchovies
40HTML Forms
- Selection list
-
- Januarytion February
- March
- April
- .
- .
- .
- December
-
41- Submit button
-
- Hidden field
- value"YYY-11543-234-9"/
- The browser does not display a hidden field
- It sends the name/value pairs in the field to
the server when the form is submitted
42HTML Forms
- Place all elements that belong to a form into a
form element method"POST"
- .
- .
- .
-
-
- 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
43Session 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
- scope"session"/
- The user requests the JSP page containing this
directive for the first time
- A new cart object is constructed
- The user returns to the same page or visits
another page in the same application
- The cart object is still alive
- If the bean directive has no scope attribute
- The bean object has page scope
- A new object is created every time the page is
visited
44Session 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
45Session Tracking
- The bean object has session scope and so holds a
list of all the cities
- Keep cities in a MultiZoneBean
- scope"session"/
- 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
- param"city"/
46Asking for the First of Several Cities
47Asking for the Next City
48Display the Time in Multiple Locations
49File multizone.html
- 01
- 02
- 03 Multiple Time Zone Form
- 04
- 05
- 06
- 07 method"POST"
- 08 First City
- 09
- 10 City"/
- 11
- 12
- 13
- 14
50File multizone.jsp
- 01 scope"session"/
- 02 value""/
- 03 param"city"/
- 04 value"
property\"times\"/"/
- 05
- 06
- 07
- 08 Multiple Time Zone JSP
- 09
- 10
- 11 Current time lookup
- 12
- 13 property"times"/
- 14
51- 15
- 16 method"POST"
- 17 Next City
- 18
- 19 City"/
- 20
- 21
- 22
- 23
52File 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.getTimeInstan
ce()
53- 18 cities new ArrayList()
- 19
- 20
- 21 /
- 22 Write-only date property.
- 23 _at_param 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.
- 32 _at_param aCity the city to add to the
city list
- 33 /
- 34 public void setCity(String aCity)
- 35
- 36 cities.add(aCity)
54- 38
- 39 /
- 40 Read-only times property.
- 41 _at_return 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 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)
55- 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
- 71 _at_param aCity the city for which to find
the time zone
- 72 _at_return the time zone or null if no
match is found
- 73 /
- 74 private static TimeZone getTimeZone(String
city)
- 75
- 76 String ids TimeZone.getAvailableIDs(
)
56- 78 if (timeZoneIDmatch(idsi, city))
- 79 return TimeZone.getTimeZone(idsi
)
- 80 return null
- 81
- 82
- 83 /
- 84 Checks whether a time zone ID matches a
city
- 85 _at_param id the time zone ID (e.g.
"America/Los_Angeles")
- 86 _at_param aCity the city to match (e.g.
"Los Angeles")
- 87 _at_return true if the ID and city match
- 88 /
- 89 private static boolean timeZoneIDmatch(Stri
ng 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
57- 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
jspforward directive to select another page
58- 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
-
-
-
-
-
-
59- 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
60File zonebranch.html
- 01
- 02
- 03 Time Zone Branch Form
- 04
- 05
- 06
- 07 City
- 08
- 09 Time"/
- 10
- 11
- 12
- 13
61File zonebranch.jsp
- 01 scope"request"/
- 02 value""/
- 03 param"city"/
- 04
- 05 if (zone.isAvailable())
- 06
- 07
- 08
- 09
- 10
- 11 else
- 12
- 13
- 14
- 15
- 16
- 17
62File zoneresult.jsp
- 01
- 02
- 03 Time Zone Branch Result
JSP
- 04
- 05
- 06 Time Zone Branch Result JSP
- 07 The current time in request.getParameter("city") is
- 08 property"time"/
- 09
- 10
- 11
63File 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 Time"/
- 14
- 15
- 16
- 17
64A 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
65A 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
66A 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
67A Three-Tier Application
- Retrieve the database information from web.xml
and initialize the database
- Any directives you place as child elements of
the jspuseBean element are executed only once
- ZoneDBBean makes a database query to find the
requested city
68File zonedb.html
- 01
- 02
- 03 Time Zone Database Form
- 04
- 05
- 06 method"POST"
- 07 City
- 08
- 09 Time"/
- 10
- 11
- 12
- 13
6901 scope"application" 02
"db" property"driver" 03 value'
lication.getInitParameter("jdbc.drivers") '/
04
05 value'
r("jdbc.url") '/ 06
"db" property"username" 07 value'
plication.getInitParameter("jdbc.username")
'/ 08
"password" 09 value'
nitParameter("jdbc.password") '/
10 11 12
e" class"ZoneDBBean"/ 13
"zone" property"city" param"city"/
14
property"connection" value"
db.getConnection() "/ 15
e"zone" property"date" value"
java.util.Date() "/ 16
7017 18 19 Zone D
atabase JSP 20 21
22 Zone Database JSP 23
The current time in
ity") is 24
zone" property"time"/ 25 26
body 27
71File 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.
- 12 _at_param driver the database driver name
- 13 /
- 14 public void setDriver(String driver)
- 15 throws ClassNotFoundException
- 16
- 17 Class.forName(driver)
72- 18
- 19
- 20 /
- 21 Write-only url property.
- 22 _at_param aUrl the JDBC URL
- 23 /
- 24 public void setUrl(String aUrl)
- 25
- 26 url aUrl
- 27
- 28
- 29 /
- 30 Write-only username property.
- 31 _at_param aUsername the database user
name
- 32 /
- 33 public void setUsername(String aUsername)
- 34
- 35 username aUsername
- 36
73- 38 /
- 39 Write-only password property.
- 40 _at_param 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.
- 49 _at_return the database connection
- 50 /
- 51 public static Connection getConnection()
- 52 throws SQLException
- 53
- 54 return
- 55 DriverManager.getConnection(url,
username, password)
- 56
74- 58 private static String url
- 59 private static String username
- 60 private static String password
- 61
75File 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.
76- 018 /
- 019 public ZoneDBBean()
- 020
- 021 timeFormatter DateFormat.getTimeInsta
nce()
- 022
- 023
- 024 /
- 025 The city property.
- 026 _at_return 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.
- 035 _at_param aCity the city for which to
report the local time
- 036 /
77- 038
- 039 city aCity
- 040
- 041
- 042 /
- 043 Write-only date property.
- 044 _at_param 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.
- 053 _at_return the formatted time
- 054 /
- 055 public String getTime() throws
SQLException
- 056
78- 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.
- 069 _at_param aCity the city for which to
find the time zone
- 070 _at_return 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
79- 078 Statement stat conn.createStatemen
t()
- 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(resul
t.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
- 096 _at_param aCity the city for which to
find the time zone
80- 098 /
- 099 private static TimeZone
getTimeZone(String city)
- 100
- 101 String ids TimeZone.getAvailableIDs
()
- 102 for (int i 0 i
- 103 if (timeZoneIDmatch(idsi, city))
- 104 return TimeZone.getTimeZone(idsi
)
- 105 return null
- 106
- 107
- 108 /
- 109 Checks whether a time zone ID matches
a city
- 110 _at_param id the time zone ID (e.g.
"America/Los_Angeles")
- 111 _at_param aCity the city to match (e.g.
"Los Angeles")
- 112 _at_return true if the ID and city match
- 113 /
- 114 private static boolean timeZoneIDmatch(Str
ing id, String city)
- 115
- 116 String idCity id.substring(id.indexOf
('/') 1)
81- 118
- 119
- 120 private Date theDate
- 121 private DateFormat timeFormatter
- 122 private String city
- 123
82Servlets
- Servlets are an alternative to JSPs for
building web applications
- JSP pages are actually translated into Servlets
- A servlet is a Java program
- It carries out computations
- And can emit data that is returned to the
browser
83Servlets
- 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)
84Servlets
- This example does not receive any request
information
- The servlet
- Obtains the current time
- Creates HTML document containing the
information
- Sends the page back to the browser
85Servlets
- 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
86Servlets
- 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
8701 import java.io.PrintWriter
02 import java.io.IOException