servlet的生命周期分为三个阶段:1、初始化阶段,调用Init函数 。2、响应客户端请求,调用servlet服务函数。3、销毁,调用destory函数
在项目对应下的web.xml中的<Servlet></Servlet>之前添加一些代码:<load-on-startup>1<load-on-startup>,服务器一启动就会创建Servlet.客户端发送请求,创建的Servlet就会从服务器中拿到内置对象request、response,并调用doget、dopost方法对请求进行服务,最后服务器终止运行时,调用destory方法,释放所占用的资源。
初始化参数:
// 初始化
// 要取得初始化参数,必须使用以下初始化方法
public void init(ServletConfig config) throws ServletException
{
// config对象中有取得初始化参数的方法:getInitParameter("参数名称")
this.usename= config.getInitParameter("usename") ;
this.password = config.getInitParameter("password") ;
String dd = config.getInitParameter("DBDRIVER") ;
System.out.println("usename => "+usename) ;
System.out.println("password => "+password) ;
System.out.println("DBDRIVER => "+dd) ;
}
Tomcat启动先创建config对象,到虚目录下询问web-inf中的web.xml,找到对应<servlet-class>中的组件,找到之后创建servlet对象,执行Init,马上把config对象的地址驻入进来,也就拿到了初始化参数

public void init(ServletConfig config) throws ServletException
{
System.out.println("** Servlet 初始化 ...") ;
}
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
System.out.println("** Servlet doGet处理 ...") ;
}
// 处理post请求
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{ this.doGet(req,resp);
System.out.println("** Servlet doPost处理 ...") ;
}
// 销毁
public void destroy()
{
System.out.println("** Servlet 销毁 ...") ;
}
网友评论