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

  • 相关阅读:
    bzoj 1031: [JSOI2007]字符加密Cipher 後綴數組模板題
    hdu3949 XOR xor高斯消元
    The xor-longest Path
    Contest20140906 反思
    Contest20140906 ProblemC 菲波拉契数制 DP
    Contest20140906 ProblemA dp+线段树优化
    bzoj 1257: [CQOI2007]余数之和sum 数学 && 枚举
    tyvj P1716
    BZOJ 1012 [JSOI2008]最大数maxnumber【线段树】
    Bzoj1083 1083: [SCOI2005]繁忙的都市【MST】
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/13500041.html
Copyright © 2020-2023  润新知