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()  

  • 相关阅读:
    java实现DAG广度优先便利
    java实现图分组
    四。字符串
    二。链表
    一。数组
    TypeScript学习(六)@types包
    TypeScript学习(五)三斜线指令
    TypeScript学习(四)声明文件和declare关键字
    TypeScript学习(三)命名空间和模块
    TypeScript学习(二)函数重载
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13500041.html
Copyright © 2011-2022 走看看