The Methods Overridden by the BasicServlet
The following four methods are overridden by the BasicServlet :
Let's take a look at each of these methods in more detail.
The init() Method
The BasicServlet defines a very simple implementation of the init() method. It takes the
ServletConfig object that is passed to it and passes it to its parent's init() method, which
stores the object for later use. The parent that actually holds on to the ServletConfig object is
the GenericServlet . The GenericServlet provides your servlet, through inheritance, with
methods to access the ServletConfig object. The code that performs this action follows:
This is a very important step. If you do not do this, you must hold the ServletConfig object
yourself. We will discuss the significance of the ServletConfig object in later chapters.
You will also notice this implementation of the init() method does not create any resources.
This is why the BasicServlet does not implement a destroy() method.
The doGet() and doPost() Methods
The BasicServlet 's doGet() and doPost() methods are identical. The only difference is the
requests they service. The doGet() method handles GET requests and the doPost() method
handles POST requests.
Both of these methods receive HttpServletRequest and HttpServletResponse objects. These
objects encapsulate the request/response paradigm. The HttpServletRequest contains infor-
mation sent from the client, and the HttpServletResponse contains information that will be
sent back to the client. The first executed line of these methods follows:
This method sets the content type for the response. You can set this response property only
once. You must set this property before you can begin writing to a Writer or an OutputStream .
In our example, we are using a PrintWriter and setting the response type to text/html .
The next thing to do is get the PrintWriter . This is accomplished by calling the
ServletResponses 's getWriter() method. This is done in the following line of code:
PrintWriter out = response.getWriter();