servlet生命周期

jsp第二章

一,什么是servlet

servlet是一个java程序,是在服务器上运行已处理客户端请求并做出响应的程序

二,servlet生命周期

servlet生命周期
实例化——servlet容器创建servlet的实例
初始化——该容器调用init()方法
服务——如果请求servlet则该容器调用service()方法
销毁——销毁实例之前调用destroy()方法
代码如下:
package org.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**

  • Servlet implementation class Second
    */
    //注解
    @WebServlet("/second")
    public class Second extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**

    • @see HttpServlet#HttpServlet()
      */
      public Second() {
      super();
      // TODO Auto-generated constructor stub
      }

    /**

    • @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      response.getWriter().append("Served at: ").append(request.getContextPath());
      System.out.println(“get请求方式”);
      }

    /**

    • @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
      */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      doGet(request, response);

    }
    @Override
    public void destroy() {
    // TODO Auto-generated method stub
    super.destroy();
    System.out.println(“销毁”);
    }
    @Override
    public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    System.out.println(“初始化”);
    }
    }

三, Javax.servlet Javax.servlet .http

servlet生命周期
servlet生命周期

上一篇:图书管理系统设计与实现(毕业设计)


下一篇:创建简单的tomcat项目