参见:http://www.boyunjian.com/javadoc/javax.servlet/javax.servlet-api/3.1.0/_/javax/servlet/Servlet.html
Servlet 类应实现 javax.servlet.Servlet 接口并实现其生命周期方法。
接口 Servlet
- 所有已知实现类:
- GenericServlet,HttpServlet
public interface Servlet
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends
or an HTTP servlet that extends
javax.servlet.GenericServletjavax.servlet.http.HttpServlet
.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
- The servlet is constructed, then initialized with the
init
method. - Any calls from clients to the
service
method are handled. - The servlet is taken out of service, then destroyed with the
destroy
method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig
method, which the servlet can use to get any startup information, and thegetServletInfo
method, which allows the servlet to return basic information
about itself, such as author, version, and copyright.
其中最主要的方法是
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ... ...}
void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
This method is only called after the servlet's init()
method has completed successfully.
The status code of the response always should be set for a servlet that throws or sends an error.
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet's class and
instance variables. More information on multithreaded programming in Java is available in
the Java tutorial on multi-threaded programming.
- 参数:
req
- theServletRequest
object that contains the client's requestres
- theServletResponse
object that contains the servlet's response- 抛出:
ServletException
- if an exception occurs that interferes with the servlet's
normal operationjava.io.IOException
- if an input or output exception occurs