CIS336 Website design, implementation and management (also

Download Report

Transcript CIS336 Website design, implementation and management (also

Lecture 8
Servlets
(Based on Møller and Schwartzbach, 2006, Chapter 9)
David Meredith
[email protected]
www.titanmusic.com/teaching/cis336-2006-7.html
CIS336
Website design, implementation and
management
(also Semester 2 of CIS219, CIS221 and
IT226)
1
Web applications and
servlets
• Last week we saw how to build a simple
Web server
– Could only generate static pages
• This week we look at how to generate
responses dynamically using servlets that
have been plugged into the server
• Servlet framework is a Java-based API for
programming Web applications
• A servlet is a program written for this API
2
Web applications:
Basic concepts
• Web server responds to http requests
• Responses can be generated by Web
applications
– contain programs that are plugged into the Web
server
• One server typically runs many concurrent
threads of each Web application
– Each thread handles one HTTP request or one
client
• A series of response-request interactions
between a server and a client is called a
session
3
Sessions
•
•
•
Client
Server
•
Request
HTML page
•
Request
Session is a sequence of related
interactions between a client and a
server
It is a thread of execution managed
by a server
Session thread stops when client
logs out or times out after client
has stopped issuing requests
HTTP is stateless, so session states
have to be managed at a higher
level
Three categories of state:
1. Shared state (global data)
–
shared between all sessions and
stored in a database on the server
2. Session state (local data)
HTML page
–
–
private to a particular session thread
e.g.,
–
–
–
session thread
contents of a shopping cart
whether client has logged in
"program pointer" of thread
3. Transient state
–
4
data that is only used in a single
interaction
A "Hello World!" Servlet
• Servlet can be run with the Apache Tomcat server
• Servlet API consists of two packages
– javax.servlet
– javax.servlet.http
• contains functionality specific to HTTP
• Servlet is usually a subclass of HttpServlet
• doGet method is invoked in response to a GET method
– takes two arguments:
• HttpServletRequest object holds information about the request
• HttpServletResponse object used to generate response
5
Servlet life cycle
• init method used to
initialize servlet when it is
constructed
– e.g., connecting to a
database
• GET request causes doGet
method to be invoked
• POST request causes
doPost method to be
invoked
• Variables in doGet and
doPost correspond to
transient state
– i.e., private to session
• When server shut down,
destroy method invoked on
each servlet
• getServletInfo method
should be implemented to
return a short descriptive
string
• log method writes
6
messages to the log
Requests
•
HttpServletRequest parameter of doGet and doPost contains
information about incoming request
•
Most important methods of HttpServletRequest are
– getHeader
• returns the value of the specified header name as a string
– e.g., request.getHeader("User-Agent")
– getParameter
• returns decoded value of a form field as a string
– e.g., request.getParameter("name")
» returns the value provided by the user to a GUI form element whose name
attribute has the value "name"
• works for GET and POST requests
• works for different encodings in POST requests
• provides useful level of abstraction
– getInputStream
• returns an input stream for accessing HTTP request body
– getRemoteHost, getRemoteAddr, getRemotePort
• return information about the client end of the TCP connection
7
Requests
•
Note use of
–
getRemoteHost (l.13)
–
getHeader (l.14)
–
getParameter (l.17)
•
POST requests are
redirected to doGet
•
htmlEscape escapes special
characters in the value
entered in the "name"
control
•
Never assume that values
from expected form fields
or request header lines are
present (see lines 15, 18)
8
Responses
• HttpServletResponse parameter of doGet and doPost
used to construct outgoing response
• Main methods in HttpServletResponse are
– setStatus
• sets response status code (default is 200)
– addHeader and setHeader
• adds or overwrites header fields
– getOutputStream
• returns output stream for writing response body
– getWriter
• returns a PrintWriter which wraps the output stream and sends
characters rather than bytes
– setContentType
• sets the Content-Type response header field
• sets character encoding for PrintWriter
– e.g., response.setContentType("text/xml;charset=UTF-8")
– sendError and sendRedirect
• simplify construction of error responses and temporary redirects
9
Servlet contexts and Shared State
•
Each Web application has a ServletContext object that holds
information about the context of a servlet
– accessible via Servlet class getServletContext method
•
ServletContext has getServerInfo method that returns information
about the server
– e.g., Apache Tomcat/5.0.30
•
Each Web application may contain many servlets and other
resources (e.g., CSS, GIFs, etc. )
•
Each Web application is associated with a context path
– Context path is base of URIs for resources in application
– Determined by deployment configuration (see later)
•
ServletContext getRealPath method computes absolute path of
resource from context path and relative path of resource
•
ServletContext can be used to store shared state
– setAttribute method binds an object to an attribute name
– getAttribute returns object bound to an attribute name
•
Data can be communicated between different Web applications
10
running on the same server by using the getContext method which
returns the ServletContext of a servlet
A Polling Service
• This Web application consists of
– an HTML file called QuickPollQuestion.html which
contains a form for entering the poll question
– a servlet called QuickPollSetup for receiving data from
the form in QuickPollQuestion.html
– a servlet called QuickPollAsk for making an HTML
page containing the question and a form which allows
the user to vote 'Yes' or 'No'
– a servlet called QuickPollVote for receiving a vote
– a servlet called QuickPollResults for showing the
11
results
QuickPollQuestion.html
• Deployment configuration (see later)
defines mapping from URI setup in
action attribute of form element to the
Deploy
QuickPollSetup
servlet
12
QuickPollSetup Servlet
• String q set to equal value entered by user
into GUI element named "question" in
QuickPollQuestion.html
• Attributes question, yes and no set in
servlet context, c
• Message sent back to user to indicate that
13
question has been registered
QuickPollAsk Servlet
• Uses question stored in servlet context to
make a new HTML form with two radio
buttons that allow the user to vote on the
question
• getAttribute returns an Object which has
14
to be cast to a String
QuickPollVote Servlet
• Receives form data from voting form
• Increments either yes or no servlet context
attributes accordingly
15
• Sends an acknowledgement to the user
QuickPollResults Servlet
• Uses tables within
tables to draw a
barchart that
represents the
responses to the
poll
• Set Cache-Control
so as to disable
caching to ensure
that new, up-todate form is
loaded, not cached
version
• Use POST in cases
where servlet has
side-effects, GET
when it doesn't 16
HttpSession objects
• HttpSession object is an abstraction of a
session that hides implementational details
of session management
• HttpServletRequest has a getSession
method which returns the current
HttpSession object
• Session terminated by
– an invocation of the invalidate method
– inactivity for a certain time interval, determined
by setMaxInactiveInterval method
• HttpSession object can be used to store
session state using setAttribute and
getAttribute methods
17
A Shopping Cart Servlet (1/2)
• cart is stored in a
TreeMap that maps
items to amounts
• cart is stored as an
attribute of the
session
• If the request
method is POST,
then an item is
added to the cart
(causes side-effect
on server)
• Returns 400 Bad
Request if cannot
parse amount
18
A Shopping Cart Servlet (2/2)
• Prints out form for
adding new item
• Prints out table
listing contents of
cart
• URLs passed
through the
encodeURL method
to ensure special
characters are
escaped
19
Web applications and deployment
• In servlets, files always organised in a common
directory structure as follows
• Assuming context path is myapp,
– myapp/ and all subdirectories except WEB-INF contain
static resources
• e.g., HTML, images, stylesheets, JSP files
– myapp/WEB-INF/ contains the deployment descriptor (see
later)
– myapp/WEB-INF/classes contains all servlet classes and
auxiliary classes used by servlets
– myapp/WEB-INF/lib contains additional jar files
• Class files must be placed in subdirectories that
match their package names
– e.g., if MyServlet.class belongs to inc.widget package,
then it is placed in myapp/WEB-INF/classes/inc/widget/
• An whole Web application can be bundled in a
single Web Archive file (.WAR) using the jar tool
20
Deployment descriptors
• Every Web application contains a
deployment descriptor
– An XML file called web.xml stored in
myapp/WEB-INF/
– Configures application by providing
• mapping from URI paths to application
resources
• initialization parameters
• error-handling configuration
• ...
21
Example Deployment Descriptor
•
•
•
display-name element provides name for the application
web-app element can contain more than one servlet and servletmapping elements
servlet element (servlet declaration)
– associates a name with a servlet class
•
can be many servlet declarations for a given servlet class
– each declaration results in an instance of the servlet being constructed
•
servlet-mapping element associates servlet name with a URI
pattern
– pattern is relative to context path
• e.g., if context path is myapp, then complete path here would be myapp/hello/
and this would cause the HelloWorld servlet to be executed
•
namespace declaration identifies deployment descriptor language
which is defined by an XML Schema definition
22
Initialization parameters
•
Context initialization parameters apply to whole application
– accessed using getInitParameter method of ServletContext object
– in deployment descriptor above, context initialization parameter, admin,
is added with the value [email protected]
•
Servlet initialization parameters apply to individual servlet instances
– accessed using getInitParameter method of HttpServlet object
– in deployment descriptor above, servlet initialization parameter,
verbose, added with value true
23