Servlet接口SUN公司定义了两个默认实现类,分别为:GenericServlet、HttpServlet。
HttpServlet指能够处理HTTP请求的Servlet,它在原有Servlet接口上添加了一些与HTTP协议处理方法,它比Servlet接口的功能更为强大。因此开发人员在开发Servlet的时候,通常应该继承这个类,而避免直接去实现Servlet接口。
HttpServlet在实现Servlet接口时,覆写了service方法,该方法体内的代码会自动判断用户的请求方式,如为GET请求,则调用HttpServlet的doGet方法,如为POST请求,则调用doPost方法。因此,开发人员在编写Servlet时,通常只需要覆写doGet或doPost方法,而不要去覆写service方法。
Servlet在线API http://tomcat.apache.org/tomcat-5.5-doc/servletapi/
public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
Defines a generic, protocol-independent
servlet. To write an HTTP servlet for use on the
Web, extend HttpServlet
instead.
GenericServlet
implements the Servlet
and ServletConfig
interfaces. GenericServlet
may be directly extended by a servlet, although it‘s more common to extend
a protocol-specific subclass such as HttpServlet
.
GenericServlet
makes writing servlets
easier. It provides simple versions of the lifecycle methods
init
and destroy
and of the methods
in the ServletConfig
interface. GenericServlet
also implements the log
method, declared in the ServletContext
interface.
To write a generic servlet, you need only
override the abstract service
method.
public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
Provides an abstract class to be subclassed to create
an HTTP servlet suitable for a Web site. A subclass of HttpServlet
must override at least
one method, usually one of these:
doGet
, if the servlet supports HTTP GET requestsdoPost
, for HTTP POST requestsdoPut
, for HTTP PUT requestsdoDelete
, for HTTP DELETE requestsinit
anddestroy
,
to manage resources that are held for the life of the servletgetServletInfo
, which the servlet uses to
provide information about itself
There‘s almost no reason to override the service
method. service
handles standard HTTP
requests by dispatching them to the handler methods
for each HTTP request type (the do
XXX
methods listed above).
Likewise, there‘s almost no reason to override the
doOptions
and doTrace
methods.
Servlets typically run on multithreaded servers,
so be aware that a servlet must handle concurrent
requests and be careful to synchronize access to shared resources.
Shared resources include in-memory data such as
instance or class variables and external objects
such as files, database connections, and network
connections.
See the Java Tutorial on Multithreaded Programming for more
information on handling multiple threads in a Java program.