Learn Java for Web Development

(Tina Meador) #1
CHAPTER 2: Building Web Applications Using Servlets and JSP 61

An HTTP request to an HttpServlet subclass goes through a number of steps:



  1. A call to the public service (ServletRequest, ServletResponse) method by
    the container.

  2. Delegation of this call to HttpServlet’s protected service
    (HttpServletRequest, HttpServletResponse) method.

  3. The protected service (HttpServletRequest, HttpServletResponse)
    method then delegates to the appropriate doXxx method, depending on the
    HTTP method used for the request.


HelloWorld Servlet


As mentioned in the previous section, the superclass of your servlet includes two versions of init(),
one that takes a ServletConfig and one that’s a no-arg. The init(ServletConfig) method calls the
no-arg init(), so you need to override only the no-arg version.


init( )


The container calls init()on the servlet instance. You can override it in order to get database
connections registered with other objects. Otherwise, the init() method from the Genericservlet runs.


Note HTTP/1.1 defines seven request methods. The HttpServlet class provides default implementations
for each of these methods that you can override in your servlets. However, most web application comprise
servlets that override only the doGet() and doPost() methods.

GenericServlet


Most servlets provide similar basic functionality through an abstract javax.servlet.GenericServlet
class provided by the Servlet API. The GenericServlet class implementation is protocol-independent,
so it does not matter if it has to respond to HTTP or FTP requests. The GenericServlet abstract
class defines an init() method that is called by the default init(ServletConfig) method to execute
any application-specific servlet initialization.


HttpServlet


In a web application, lack of any protocol-dependent processing in a GenericServlet class signifies
that the developer has to write the code for this processing in any subclass she creates. Since
HTTP is the most well-known and widely used protocol on the Web, the Servlet API also includes
one more abstract subclass of GenericServlet: javax.servlet.http.HttpServlet. The service()
method is implemented by HttpServlet, which inspects the incoming HTTP method and invokes the
appropriate method for that request type.

Free download pdf