servlet调用流程
- 加载和实例化
- 初始化
- 处理请求
- 终止服务
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
1. @author lihuaqing
2. @create 2019-01-29 22:43
**/
@WebServlet("/lifecycle")
public class LifeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
System.out.println("doPost....");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
System.out.println("doGet....");
}
public LifeServlet() {
super();
System.out.println("LifeServlet....");
}
@Override
public void init() throws ServletException {
super.init();
System.out.println("init....");
}
@Override
public void destroy() {
super.destroy();
System.out.println("destroy....");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
System.out.println("service....");
}
}
连续调用两次结果
loadOnStartup控制启动顺序
@WebServlet(urlPatterns = "/lifecycletwo",loadOnStartup = 2)
@WebServlet(urlPatterns = "/lifecycle",loadOnStartup = 1)
加载顺序结果
总结
- servlet 是单例模式
- loadOnStartup 当为负数时,不随容器启动而加载
- loadOnStartup 当为0或者正数时,随容器启动而加载
- loadOnStartup 值越小,优先级越高
- loadOnStartup 默认值为-1