创建并部署一个Servlet,要求在Servlet生命周期的每一个阶段输出一行调试信息。

Servlet.java代码如下:

packagecn.edu.qfnu.ch06.servlet;

importjava.io.IOException;

importjavax.servlet.ServletConfig;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

publicclass LifeServlet extends HttpServlet {

    private static final long serialVersionUID =1L;

        public LifeServlet() {

        super();

        // TODO Auto-generated constructor stub

    }

        public void init(ServletConfig config) throwsServletException {

        System.out.println("init()方法被调用!");

    }

    public void destroy() {

        System.out.println("destroy()方法被调用!");

    }

    protected void service(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("service()方法被调用!");

    }

       protected void doGet(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("doGet()方法被调用!");

    }

    protected void doPost(HttpServletRequestrequest, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("doPost()方法被调用!");

    }

}

Web.xml代码如下:

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"version="3.0">

  <display-name>shiyanliude</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

    <description></description>

    <display-name>LifeServlet</display-name>

    <servlet-name>LifeServlet</servlet-name>

    <servlet-class>cn.edu.qfnu.ch06.servlet.LifeServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>LifeServlet</servlet-name>

    <url-pattern>/LifeServlet</url-pattern>

  </servlet-mapping>

</web-app>

在浏览器中输入:http://localhost:8080/shiyanliude/LifeServlet

eclipse中的console

第一次请求时:

spacer.gif

        1

再次请求时输出结果:

spacer.gif

      2

重新启动服务器时,输出结果:

spacer.gif

        3


你可能感兴趣的:(servlet,生命周期)