上面是web.xml 下麵是servletlife java類 ...
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>servletlife</servlet-name> <servlet-class>com.sxt.in.servletlife</servlet-class> <load-on-startup>1</load-on-startup><!-- 載入伺服器啟動流 --> </servlet> <servlet-mapping> <servlet-name>servletlife</servlet-name> <url-pattern>/life</url-pattern> </servlet-mapping> </web-app>
上面是web.xml
下麵是servletlife java類
package com.sxt.in; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet生命周期 * 1從第一次被調用到伺服器結束 * 2如果Servlet在xml中配置了load-on-startup生命周期為, 從伺服器啟動到伺服器關閉 * 註意: * init方法是對servlet進行初始化的一個方法會在servlet第一次進行存儲時執行 * destory方法是servlet被銷毀時執行,也就是伺服器關閉的時候 * * @author Administrator * */ public class servletlife extends HttpServlet { @Override//初始化方法在servlet第一次載入內容時被調用 public void init() throws ServletException { System.out.println("servlet 初始化完成"); } @Override//service方法是真正處理請求的方法 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("servlet life");//servlet只要伺服器在他就在 System.out.println("servlet life"); } @Override public void destroy() { System.out.println("我被銷毀了"); } }