COMP 405
Spring 2014

Java Servlets

Home  Info  Owlspace  Java Resources  Eclipse Resources  SharePoint  Piazza

On a single application server, only one instance of a servlet is needed.   The server instantiates the servlet the first time that it is accessed and then runs multiple threads through it, one for each request, for subsequent accesses:


(From "Servlet Life Cycle" at XpertTeach.com)

In general, the application server is free to destroy the servlet object if if feels that it has not been accessed in a long enough period time and the server wishes to regain the memory and other resources tied up by that servlet object.   This issue is even more important in a cloud environment where multiple servlet instances may be spread across many servers.   For  any request, any subsequent requests may be routed to a completely different servlet instance.   Likewise, the cloud may be dynamically instantiating and destroying servlet and application server instances to handle changing loads.

Do NOT make any assumptions about data persistence inside of a servlet!

In Google App engine, one can define a servlet class and create a URL route in the application's app.yaml file to route requests to instances of that servlet.   Note that for Java ServerPages (JSPs), the definition of, instantiation of and routing to the servlet is done automatically, dynamically and behind the scenes.   When manually defining a servlet, one typically subclasses javax.servlet.http.HttpServlet to define a servlet.

The main methods of interest in an HTTPServlet are doGet() and doPost() as these are the two most common types of web requests.   Both methods take the same 2 parameters:  a HttpServletRequest and a HttpServletResponse.   The HttpServletRequest parameter holds all the information about the request, including any query string (individual query parameters are also accessible separately), login and/or session information, etc.  The HttpServletResponse parameter is used by teh servlet to send data back to the requestor.  It contains methods to set the headers of the response, get the stream or writer for outputting the body of the response, etc.

References:


© 2013 by Stephen Wong