Servlet LifeCycle
- A servlet engine loads and initializes the servlet
- The Servlet handles zero or more client requests, each as a separate thread.
- The Servlet engine removes the servlet from its memory. Unload sometime occurs when the servlet engine shuts down
- Initially when the servlet starts - the servlet initializes using the init() method.
- Then client requests are handled.
The client requests are handled thru the service() method which supports HTTP requests by using the following methods:
- Overridden methods
doGet()
doPost()
doPut()
doDelete()
- Generally not overridden:
doOption() - handles OPTIONS request. The HTTP Options are determined automatically by this method.
doTrace() - handles the Trace request. The response typically contains all of the headers in the trace request
- When the server removes the servlet it runs the destroy() method.
HTTPServletRequest Object
Provides access to HTTP header data such as:
- cookies
- the HTTP method with which the request is made
- access to the args that the client sent as part of the request.
Methods:
- getparameter() - returns value of named parameters
- getParameterValues() - returns the array of values for the named parameter
- getParameterNames() - returns the names of the parameters
- getQueryString() returns a String of raw data from the client
FOR HTTP POST, PUT and DELETE requests:
The text data is handled by getReader() method that provides you with BufferedReader object to read the raw data.
The binary data is handled in getInputStream() method that provides a ServletInputStream to read the raw data.
HTTPServletResponse Object
Two ways are available for returning the data from the user:
-
getWriter() method returns a writer for text data
-
getOutputStream returns a ServletOutputStream for binary data
Close these streams lets the server know that the response is complete.
Debugging Servlets
- Look at the HTML Source - to see if the tags are coded properly.
- Return error pages to the client - typically send error code -
- Look at the server running in command line for any apparent errors when the call to the servlet is made.
- HTTPServlet object has a method called log that allows you to log information to the server. Location of the file is specific to Servlet Engines
- Print out request data separately
- Print out response data separately.
- Restarting the webserver is also a good idea: unless the webserver support automatic reload.
Here is a simple example: Responselet.java that accepts
data from a simple HTML form form1.html.