Servlet understanding

Servlet is essentially a Java interface:

狭义上servlet是一个java的接口,广义上servlet是指实现这个接口的类;

Insert picture description here

What is this interface for?

实际上我们通过这个接口定义了一套处理网络请求的规范;
所有的servlet都要实现接口定义的那五个规范;
servlet就是接受请求、发送响应,来创建动态web应用;
package javax.servlet;

import java.io.IOException;

public interface Servlet {
    
    
    void init(ServletConfig var1) throws ServletException;

    ServletConfig getServletConfig();

    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    String getServletInfo();

    void destroy();
}

init service destruction is a life cycle method;

init()方法:
在Servlet的生命周期中,仅执行一次init()方法,它是在服务器装入Servlet时执行的,可以配置服务器,以在启动服务器或客户机首次访问Servlet时装入Servlet。无论有多少客户机访问Servlet,都不会重复执行init();
调用这个方法时,servlet容器会传入一个ServletConfig;
service()方法:
他是servlet的核心
每当请求servlet时,servlet容器就会调用这个方法;
通过上面的代码,我们知道会有ServletRequest和ServletReponse两个参数传入
ServletRequest代表一个HTTP请求,请求在内存中是一个对象,这个对象是一个容器,可以存放请求参数和属性。
ServletReponse也是由容器自动创建的,代表Servlet对客户端请求的响应,响应的内容一般是HTML,而HTML仅仅是响应内容的一部分。
destory()方法:
仅执行一次,在服务器端停止且卸载Servlet时执行该方法,有点类似于C++的delete方法。一个Servlet在运行service()方法时可能会产生其他的线程,因此需要确认在调用destroy()方法时,这些线程已经终止或完成。
 

img

The other two methods in Servlet are non-lifecycle methods, namely getServletInfo and getServletConfig:

getServletInfo, this method will return the description of the servlet. You can return any string that is useful or null.

getServletConfig, this method will return the ServletConfig passed to the init method by the Servlet container. However, in order for getServletConfig to return a non-null value, the ServletConfig passed to the init method must be assigned to a class-level variable.

Guess you like

Origin blog.csdn.net/qq_43549291/article/details/111769643