《Java Servlet编程》笔记(servlet生命周期)

类别:Java 点击:0 评论:0 推荐:

servlet生命周期高度灵活.servlet容器惟一必须严格遵守的规则就是以下的生命周期约定:
□ 生成并初始化servlet
□ 处理客户请求
□ 卸载servlet并进行无用单元收集

对应上述约定的,我们在应用中,有以下方法:
□ init()方法:负责初始化servlet对象
□ service()方法:负责响应客户请求;
□ destroy()方法:当servlet对象退出生命周期时,负责释放占用资源;

一个实例,计数器实例,在web.xml进行计数值的初始化
file://InitCounter.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InitCounter extends HttpServlet{
 
  int count;
 
  public void init() throws ServletException
  {
 String initial=getInitParameter("initial");
 try{
 count=Integer.parseInt(initial);
 }
 catch(NumberFormatException e){
 count=0;
 }
  }
  
  public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
  {
 res.setContentType("text/html");
 PrintWriter out=res.getWriter();

 count++;
 out.println("since loading this servlet instance has been accessed  "+count+"  times");
  }
 
  public void destroy(){
 super.destroy();
  }
}

file://web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <servlet>
 <servlet-name>couner</servlet-name>
        <servlet-class>InitCounter</servlet-class>
        <init-param>
  <param-name>initial</param-name>
         <param-value>1000</param-value>
        </init-param>
   </servlet>
   <servlet-mapping>
 <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
   </servlet-mapping>
</web-app>

本文地址:http://com.8s8s.com/it/it15894.htm