Servlet的三种方式:一个实现,两个继承过程,如下:
- 1.创建servlet对象(Tomcat执行)
- 2.第一次访问servlet时执行
- init()方法 该方法只执行一次
- service()方法
- 3.之后每访问一次 就执行一次service()方法
- 4.关闭服务时调用destroy()方法 该方法只执行一次
*servlet的服务周期
*1.创建
*2.初始化
*3.服务
*4.销毁:
(1)实现Servlet接口
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class testServlet1 implements Servlet {
/**
* 销毁方法
*/
public void destroy() {
System.out.println("这是销毁方法!");
}
/**
* 初始化方法
*/
public void init(ServletConfig arg0) throws ServletException {
System.out.println("这是初始化方法!");
}
/**
* 服务方法
*/
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("这是服务方法!");
}
//获取servlet配置信息
public ServletConfig getServletConfig() {
return null;
}
//获取servlet信息
public String getServletInfo() {
return null;
}
}
(2)继承GenericServlet
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class testServlet2 extends GenericServlet{
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
System.out.println("这是服务方法!");
}
(3)继承HttpServlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testServlet3 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是get方法提交");
doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("这是post方法提交");
}
}