Download Servlets - itk.ilstu.edu

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 the functionality of the Web
server. Servlets can:
– generate HTML dynamically to be returned to
the client in response to some request
– act as a communication gateway to other
resources on the server, e.g. databases, other
applications, etc.
Servlets (2)
– coordinate connections from a number of
clients
– open a separate connection from the server to
an applet on the browser using a "state-full"
protocol, e.g. IIOP, RMI, TCP/IP
– provide additional (customized) processing for
the server's standard routines
– filter data to be delivered to client applet
Servlets (3)
• Servlets are a superior solution over
alternative technologies, e.g. CGI and
server specific APIs:
– Better performance (same address space); no,
per request, process startup time
– Written in Java -- better performance than
scripting languages, e.g. PERL or Unix shell
scripts
– More portable (write-once run-on-any-server)
– Stronger security model
Servlet Lifecycle
• The lifecycle of a servlet begins when it is
loaded into a Web server and ends when it is
terminated or is reloaded.
• When a servlet is loaded, the server creates an
instance of the servlet and calls the servlet
init() method.
• A servlet may be loaded:
– automatically at server startup
– at first client request
– when a servlet is reloaded
Servlet Lifecycle (2)
• When a client request arrives at the server, the server creates a
Request object and a Response object that are specific to that
client request.
• The server then invokes the servlet's service() method, passing
both the Request and Response objects as parameters.
• The servlet gets information about the request from the Request
object, processes the request, and uses methods of the Response
object to return a response to the client.
• The service() method may invoke other methods during the
processing of the request, e.g. doGet(), doPost(), or additional
methods you write.
• When the server no longer needs the servlet, the server invokes
the servlet's destroy() method.
Servlets and Java SDK API
• The basic JavaServer API is provided in two Java
packages, javax.servlet and javax.servlet.http.
• To create a servlet, extend javax.servlet.http.HttpServlet. (The
HttpServlet class is a subclass of GenericServlet and has
specialized methods for interacting with data transferred by
the Web browser.)
• There are two methods for passing information to the
server from the browser.
– These methods, GET and POST, differ primarily in the manner in
which the data is supplied. For the GET method, data is encoded
and sent along as part of the URL. In the POST method, the data is
also encoded but is supplied as a separate data "packet", not part of
the URL.
Servlets and Java SDK API (2)
• The default behavior of the service() method of
HttpServlet determines whether the information sent with
the request is being provided by GET or POST. If the
information is being provided by GET, the service()
method invokes the doGet() method. If the information is
being provided by POST, the service() method invokes the
doPost() method.
HttpServletRequest Objects
• Provides access to HTTP header data (e.g.,
cookies found, HTTP method, arguments that the
client sent as part of the request).
• To access client data:
– The getParameter method returns the value of a
named parameter. If your parameter could have more
than one value, use getParameterValues instead.
– The getParameterValues method returns an array of
values for the named parameter. (The method
getParameterNames provides the names of the
parameters.)
HttpServletRequest Objects (2)
– For HTTP GET requests, the getQueryString method
returns a String of raw data from the client. You must
parse this data yourself to obtain the parameters and
values.
– For HTTP POST, PUT, and DELETE requests,
• If you expect text data, the getReader method returns a
BufferedReader for you to use to read the raw data.
• If you expect binary data, the getInputStream method
returns a ServletInputStream for you to use to read the
raw data
HttpServletResponse Objects
• An HttpServletResponse object provides two ways
of returning data to the user:
– The getWriter method returns a Writer
• Use the getWriter method to return text data to the user
– The getOutputStream method returns a
ServletOutputStream
• Use the getOutputStream method for binary data.
• Closing the Writer or ServletOutputStream after
you send the response allows the server to know
when the response is complete.
Handling GET and POST Requests
• To handle HTTP requests in a servlet,
extend the HttpServlet class and override
the servlet methods that handle the HTTP
requests that your servlet supports.
– Handling GET requests involves overriding the
doGet method.
– Handling POST requests involves overriding
the doPost method.
Handling GET Request
public class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" + "<head><title>Book Description</title></head>" + ...);
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
Handling POST Request
public class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" + "<head><title> Receipt </title>" + ...);
out.println("<h3>Thank you for purchasing your books from us " +
request.getParameter("cardname") +
...);
out.close();
}
...
}
Session Tracking
• Session tracking is a mechanism that servlets use
to maintain state about a series of requests from
the same user (that is, requests originating from
the same browser) across some period of time.
• Sessions are shared among the servlets accessed
by a client. This is convenient for applications
made up of multiple servlets.
• To use session tracking,
– Get a session (an HttpSession object) for a user.
– Store or get data from the HttpSession object.
– Invalidate the session (optional).
Obtaining a Session
• The getSession method of the HttpServletRequest
object returns a user's session.
• When you call the method with its create
argument as true, the implementation creates a
session if necessary.
• To properly maintain the session, you must call
getSession before any output is written to the
response.
Storing/Getting Data from a Session
• The HttpSession interface provides methods
that store and return:
– Standard session properties, such as a session
identifier
– Application data, which is stored as a namevalue pair, where the name is a String and the
value is an object in the Java programming
language. (This is like java.util.Dictionary.)
Storing/Getting Data from a Session (2)
• Because multiple servlets have access to a user's session,
you should adopt a naming convention for organizing the
names associated with application data. This avoids
servlets accidentally overwriting each other's values in the
session.
• One such convention is servletname.name where
servletname is the full name of the servlet, including its
packages (e.g., com.acme.WidgetServlet.state is a cookie
with the servletname com.acme.WidgetServlet and the
name state).
Tracking Session: Example
public class CatalogServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());
// If the user has no cart, create a new one
if (cart == null) {
cart = new ShoppingCart();
session.putValue(session.getId(), cart);
}
...
}
}
References
• Mary Campione, Kathy Walrath, The Java
Tutorial Second Edition: Object-Oriented
Programming for the Internet, AddisonWesley, 1998.
• IBM Introduction to Servlets, Online
tutorial, 1999.