servlet生命周期
为简洁,本例使用注解方式来测试,代码部分很简单,只需要新建一个serlet,继承自HttpServlet,重写init,doGet,doPost,destory方法即可,使用注解@WebServlet注解分别测试存在loadOnStartup 和不存在loadOnStartup情况
package com.demo; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet(value = "/my", loadOnStartup = 0)
public class MyServlet extends HttpServlet { public MyServlet() {
System.out.println("create");
} @Override
public void init() throws ServletException {
System.out.println("init");
} @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service");
} @Override
public void destroy() {
System.out.println("destory");
} }
一、当配置有loadOnStartup且值大于等于0时,web服务器启动即会创建和初始化该servlet,且loadOnStartup数值越小,越优先执行,后续每次访问该servlet,将会调用一次service服务(doGet/doPost),关闭web服务,调用destory方法,销毁servlet
二、当未配置loadOnStartup时,web服务器启动时不会初始化该servlet,当第一次访问该servlet时,才会进行创建并初始化,后续每次访问该servlet,都将会调用一次service服务(doGet/doPost),关闭web服务,调用destory方法,销毁servlet。
三、servlet中init和destory方法每次都执行一次,servlet为单实例,但并没有使用单例模式
获取初始化参数
在注解@WebServlet中可添加初始化参数initParams
@WebServlet(value = "/my", loadOnStartup = 0, initParams = {
@WebInitParam(name = "name", value = "val", description = "desc"),
@WebInitParam(name = "init", value = "initValue") })
public class MyServlet extends HttpServlet {
......
}
servlet提供了一些方法来处理初始化参数,这些方法被定义到接口ServletConfig中,
可通过getInitParameter(String)获取具体某个参数的值,也可以通过遍历来获取所有初始化参数的值
@Override
public void init() throws ServletException {
System.out.println("init");
Enumeration<String> initParameterNames = this.getInitParameterNames(); while (initParameterNames.hasMoreElements()) {
String nextElement = initParameterNames.nextElement();
System.out.println(this.getInitParameter(nextElement));
} }