There are three ways to create a servlet.
Let's look at the first one to implement the Servlet interface.
Because the Servlet interface is implemented, we need to implement the methods in the interface.
Below we also explain the implementation of the servlet, the servlet lifecycle.
//servlet lifecycle: From the servlet was created to the servlet destroyed process//once created, everywhere service//A servlet will only have one object, service all requests * * 1. Instantiating (creating objects using construction methods) * 2. Initialize Execute init method * 3. Service Execution Method * 4. Destroy execution Destroy Method * * Public class ServletDemo1 implements servlet {//public ServletDemo1 () {}//Lifecycle method: When the servlet is first created, the method executes only one public void init for the entire lifecycle (serv
Letconfig arg0) throws Servletexception {System.out.println ("=======init=========");
//Life Cycle Method: A method that responds to the client, which is executed multiple times, each time the servlet is requested to execute the method public void service (ServletRequest arg0, Servletresponse arg1)
Throws Servletexception, IOException {System.out.println ("hehe");
///Life cycle Method: Executes the method public void Destroy ("******destroy**********") {System.out.println () when the servlet is destroyed;
//The servlet is destroyed when Tomcat is stopped.
Public ServletConfig Getservletconfig () {return null;
Public String Getservletinfo () {return null; }
}
The second method of creating the servlet inherits the Genericservlet class, which implements the method of the Servlet interface in addition to the service.
But we rarely use this method.
The public class ServletDemo2 extends Genericservlet {
@Override
the public void service (ServletRequest arg0, Servletresponse arg1)
throws Servletexception, IOException {
System.out.println ("Heihei");
}
The third way to create a servlet is a method that we often use
Inheritance HttpServlet method
Here are just a few three ways to create the servlet, and we'll talk more about the application in more detail.
public class ServletDemo3 extends HttpServlet {@Override protected void doget (HTTPSERVL Etrequest req, HttpServletResponse resp) throws Servletexception, IOException {System.out.println ("Ha
Ha "); @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexc
Eption, IOException {System.out.println ("ee");
Doget (REQ,RESP); }
}