zoukankan      html  css  js  c++  java
  • Servlet 05: Servlet生命周期方法

    以TestServlet.java 为例:

      @WebServlet("/TestServlet")
      public class TestServlet extends HttpServlet {

        public TestServlet() {
          System.out.println("构造方法被调用了!");
        }

        @Override
        public void init() throws ServletException {
          super.init();
          System.out.println("init()被调用了!");
        }

        @Override
        public void destroy() {
          super.destroy();
          System.out.println("destroy()被调用了!");
        }

        

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doGet");
        }


        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          System.out.println("doPost");
        }

      }

    <1>操作: Run on Server

    效果 - 第一次访问:

     (destroy方法并没有被调用)

    效果 - 刷新页面若干次:

     (只调用了doGet)

    效果 - 通过别的客户端(浏览器)访问 (代表一个新的用户来了):

      还是只调用了doGet

    <2>操作: 停止运行Tomcat

     效果:  

      destroy()被调用了

    <3>  在TestServlet.java中:

      @Override
      protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

        System.out.println("service()被调用了!");
        super.service(arg0, arg1);
      } // 不管Servlet调用的是doGet()还是doPost(), service()都会被调用

      效果:

      对代码进行一点(顺序上的)修改:

      @Override
      protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {

        super.service(arg0, arg1);  

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

      }

     效果:

     原因: super.service(arg0, arg1); 调用了doGet()  

  • 相关阅读:
    在 MAC 下配置 Nginx
    Color Schema 配色随笔
    .Net与 WebAssembly 随笔
    关于Xamarin、Qml、数据绑定、MVC、MVVM 相关的散讲
    用Nuget部署程序包
    Qt3D
    Qt3D Shader
    Qt QML 2D shader
    LearnOpenGL
    Qt3D 5.9 and future
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13500041.html
Copyright © 2011-2022 走看看