Sun Java System Web Server 7.0 Developer's Guide to Java Web Applications

Overriding Service, Get, and Post

When a request is made, Sun Java System Web Server 7.0 sends incoming data to the servlet engine to process the request. The request includes form data, cookies, session information, and URL name-value pairs, all in a type HttpServletRequest object called the request object. Client metadata is encapsulated as a type HttpServletResponse object called the response object. The servlet engine passes both objects as the servlet's service() method parameters.

The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, and GET). For example, HTTP POST requests are routed to the doPost() method, HTTP GET requests are routed to the doGet() method. This routing enables the servlet to perform different request data processing depending on the transfer method. Because the routing takes place in service(), you do not need to override service() in an HTTP servlet. Instead, override doGet(), anddoPost() depending on the expected request type.

The automatic routing in an HTTP servlet is based on a call to request.getMethod(), which provides the HTTP transfer method.

Override the service() method for generic servlets or the doGet() or doPost() methods for HTTP servlets to perform tasks needed to answer the request. Very often, these tasks collate the needed information (in the request object or in a JDBC result set object), and then passing the newly generated content to a JSP for formatting and delivery back to the client.

Most operations that involve forms use either a GET or a POST operation, so for most servlets you override either doGet() or doPost(). Implement both methods to provide for both input types or pass the request object to a central processing method, as shown in the following example:


public void doGet (HttpServletRequest request,
                  HttpServletResponse response)
         throws ServletException, IOException {
   doPost(request, response);
}

All request-by-request traffic in an HTTP servlet is handled in the appropriate doOperation() method, including session management, user authentication, JSP pages, and accessing Sun Java System Web Server 7.0 features.

If a servlet calls the RequestDispatcher method include() or forward(), the request information is no longer sent as HTTP POST, and GET. In other words, if a servlet overrides doPost(), it may not process other servlets if the calling servlet happens to receive its data through HTTP GET. For this reason, be sure to implement routines for all possible input types. RequestDispatcher methods always call service().

For more information, see Calling a Servlet Programmatically.