<?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("我被销毁了"); } }