1, Introduction: Servlet programming is implemented through the classes and interfaces of the two packages javax.Servlet and javax.servlet.http. The javax.servlet.Servlet interface is crucial. All Servlet must implement this interface or inherit a class that implements this interface.
2. The Servlet interface has 5 methods:
public void init(ServletConfig config) throws ServletException;
public void service(ServletRequest request, ServletResponse response) throes ServletException, IOException;
public void destroy();
public ServletConfig getServletConfig();
public String getServletInfo();
3. Servlet declaration cycle methods: init, service, destroy
(1) init: After the Servlet class has been initialized, the init method Will be called by the servlet container. The init method is only called once, indicating that the servlet has been loaded into the service. The init method must complete successfully before the servlet can successfully receive any requests. Servlet programmers can override this method to write initialization code that only needs to be run once, such as shelves, database drivers, value initialization, etc. In other cases, the method is empty.
(2) Servlet, the servlet container calls the service method to the servlet container. This method receives a ServletRequest parameter and a ServletResponse parameter. The Servlet Request object is used to pass the client's request parameters to the servlet, and the ServletResponse object is responsible for encapsulation. Servlet response. During the servlet life cycle, the service() method will be called multiple times.
(3) Destroy, used to remove a servlet instance from the server, usually used when the servlet container is shutting down or the servlet container needs some free memory, only when the service methods of all servlet containers have exited or timed out. This method is only called when it is eliminated. After the servlet container has called the destroy method, the service method will not be called again in the same servlet. The destroy method provides an opportunity to clean up any occupied resources, such as memory, file handles and threads, and ensure that any persistent The localization state is synchronized with the current state of the servlet's memory.
4. The working process of the Servlet container for each servlet's HTTP request
(1) When the servlet is called for the first time, load The servlet class calls the servlet's init method (only once)
(2) For each request, construct a javax.servlet.ServletRequest instance and a javax.servletServletResponse instance.
(3) Call the service method of the servlet and pass the ServletRequest and ServletResponse objects at the same time.
(4) When the servlet class is closed, call the destroy method of the servlet and unload the srvlet class.
The above is the detailed content of Tomcat——Simple Servlet container. For more information, please follow other related articles on the PHP Chinese website!