Servlets are created in three ways

1. There are three ways to create a Servlet

1. Implement the Servlet interface

Because we are implementing the Servlet interface, we need to implement the methods in the interface.

Below we also illustrate the execution process of Servlet, that is, the life cycle of Servlet.

//Servlet的生命周期:从Servlet被创建到Servlet被销毁的过程
//一次创建,到处服务
//一个Servlet只会有一个对象,服务所有的请求
/*
 * 1.实例化(使用构造方法创建对象)
 * 2.初始化  执行init方法
 * 3.服务     执行service方法
 * 4.销毁    执行destroy方法
 */
public class ServletDemo1 implements Servlet {

    //public ServletDemo1(){}

     //生命周期方法:当Servlet第一次被创建对象时执行该方法,该方法在整个生命周期中只执行一次
    public void init(ServletConfig arg0) throws ServletException {
                System.out.println("=======init=========");
        }

    //生命周期方法:对客户端响应的方法,该方法会被执行多次,每次请求该servlet都会执行该方法
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("hehe");

    }

    //生命周期方法:当Servlet被销毁时执行该方法
    public void destroy() {
        System.out.println("******destroy**********");
    }
//当停止tomcat时也就销毁的servlet。
    public ServletConfig getServletConfig() {

        return null;
    }

    public String getServletInfo() {

        return null;
    }
}

2. Inherit the GenericServlet class

It implements the method of Servlet interface except service, but we rarely use this method.

public class ServletDemo2 extends GenericServlet {

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("heihei");

    }
}

3. Inherit the HttpServlet method

public class ServletDemo3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("haha");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("ee");
        doGet(req,resp);
    }

}

The third way to create a Servlet is the one we often use

2. About the relationship between HttpServlet, GenericServlet and Servlet

For a Servlet class, the most commonly used method in our daily life is to inherit from the HttpServlet class, which provides Http-related methods. HttpServlet extends the GenericServlet class, and the GenericServlet class implements the Servlet class and ServletConfig class.

Servlet

The Servlet class provides five methods, including three lifecycle methods and two common methods. I won’t go into details about the methods of the Servlet class. I will mainly add the implementation ideas of the other two classes.

GenericServlet

GenericServlet is an abstract class that implements the Servlet interface and provides default implementations for init(), destroy() and service(). In GenericServlet, the following tasks are mainly completed:

  •  Assign the ServletConfig in init() to a class-level variable, which can be obtained by getServletConfig;
  •  Provide default implementations for all Servlet methods;
  •  You can directly call the method in ServletConfig;

The basic structure is as follows:

abstract class GenericServlet implements Servlet,ServletConfig{
 
   //GenericServlet通过将ServletConfig赋给类级变量
   private trServletConfig servletConfig;
 
   public void init(ServletConfig servletConfig) throws ServletException {

      this.servletConfig=servletConfig;

      /*自定义init()的原因是:如果子类要初始化必须覆盖父类的init() 而使它无效 这样
       this.servletConfig=servletConfig不起作用 这样就会导致空指针异常 这样如果子类要初始化,
       可以直接覆盖不带参数的init()方法 */
      this.init();
   }
   
   //自定义的init()方法,可以由子类覆盖  
   //init()不是生命周期方法
   public void init(){
  
   }
 
   //实现service()空方法,并且声明为抽象方法,强制子类必须实现service()方法 
   public abstract void service(ServletRequest request,ServletResponse response) 
     throws ServletException,java.io.IOException{
   }
 
   //实现空的destroy方法
   public void destroy(){ }
}

The above is the general implementation idea of ​​GenericServlet. We can see that if we inherit this class, we must rewrite the service() method to process the request.

HttpServlet

HttpServlet is also an abstract class. It further inherits and encapsulates GenericServlet, which makes it easier to use. Because it extends the content of Http, it also needs to use HttpServletRequest and HttpServletResponse. These two classes are subclasses of ServletRequest and ServletResponse respectively. code show as below:

abstract class HttpServlet extends GenericServlet{
 
   //HttpServlet中的service()
   protected void service(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse){
        //该方法通过httpServletRequest.getMethod()判断请求类型调用doGet() doPost()
   }
 
   //必须实现父类的service()方法
   public void service(ServletRequest servletRequest,ServletResponse servletResponse){
      HttpServletRequest request;
      HttpServletResponse response;
      try{
         request=(HttpServletRequest)servletRequest;
         response=(HttpServletResponse)servletResponse;
      }catch(ClassCastException){
         throw new ServletException("non-http request or response");
      }
      //调用service()方法
      this.service(request,response);
   }
}

We can see that HttpServlet performs default operations on the methods in the original Servlet, and does not require explicit destruction initialization and service(). In HttpServlet, a new service() method is customized, which is passed The getMethod() method judges the type of the request, and thus calls doGet() or doPost() to process get and post requests. Users only need to inherit HttpServlet, and then rewrite the doPost() or doGet() method to process the request.

We generally define a servlet by inheriting from HttpServlet.

Guess you like

Origin blog.csdn.net/qq_30436011/article/details/129393600