Java Reference
In-Depth Information
When a servlet instance is created, its
init()
method is invoked. The
init()
method allows a servlet to initialize itself before the first request is processed.
You can specify
init() p
arameters to the servlet in the
web.xml
file or via
annotations.
1.
The web container calls the
init()
method of the servlet (only once in the
servlet's life), and the
init()
method must complete before the container can
call
service()
method.
2.
service( )
The container calls the
service()
method of the servlet. This method looks at the request,
determines the type of HTTP method, and invokes the matching
doGet()
or
doPost()
on the servlet.
You never override it. Your job is to override
doGet()
or
doPost()
and let the service implementation
from
HTTPServlet
worry about calling the right one.
When the
service()
method is called on your servlet, it will be handed
references to
HttpServletRequest
and
HttpServletResponse
objects that
implement the
HttpServletRequest
and
HttpServletResponse
interfaces.
The container implements these interfaces.
service()
method
is called. For
HttpServlet
subclasses, one of the
doGet()
,
doPost()
, and
so on, methods is typically called. The container creates two objects:
HTTPServletRequest
and
HttpServletResponse
.
The
For every request received to the servlet, the servlet's
service()
method can be called multiple times as long as the servlet is
active in the servlet container.
service()
methods call
doGet()/doPost()
. You always override at least one
of them in your servlet.
The
destroy( )
The servlet container calls the
destroy()
method on the servlet, and this method is called only
once. This method provides the servlet with an opportunity to release acquired resources before
it is destroyed.
ServletContext and ServletConfig
After the
init()
method is called, the servlet gets one
ServletConfig
object per servlet and one
ServletContext
per web application. In a distributed environment, you will have one
ServletContext
per JVM. A
ServletContext
is a means by which a servlet can connect with both the container
and the other parts of the web application. In the servlet, the only time you have to go through the
ServletConfig
to get the
ServletContext
is if your servlet is not an
HttpServlet
or a
GenericServlet
.