zoukankan      html  css  js  c++  java
  • 如何创建Servlet

    //Servlet的生命周期:从Servlet被创建到Servlet被销毁的过程

    //一次创建,到处服务

    //一个Servlet只会有一个对象,服务所有的请求

    /* * 1.实例化(使用构造方法创建对象)

    * 2.初始化 执行init方法

    * 3.服务 执行service方法

    * 4.销毁 执行destroy方法

    */

    public class ServletDemo1 implements Servlet { //public ServletDemo1(){}

    //生命周期方法:当Servlet第一次被创建对象时执行该方法,该方法在整个生命周期中只执行一次

    public void init(ServletConfig arg0) throws ServletException { System.out.println("=======init========="); }

    //生命周期方法:对客户端响应的方法,该方法会被执行多次,每次请求该servlet都会执行该方法 public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { System.out.println("hehe"); }

    //生命周期方法:当Servlet被销毁时执行该方法 public void destroy() { System.out.println("******destroy**********"); }

    //当停止tomcat时也就销毁的servlet。 public ServletConfig getServletConfig()

    { return null; } public String getServletInfo() { return null; } }



    创建servlet的第二种方法,继承GenericServlet类,它实现了Servlet接口除了service的方法。
    不过这种方法我们极少用

    public class ServletDemo2 extends GenericServlet { @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {

      System.out.println("heihei");

    }

    }



    创建servlet的第三种方法,也是我们经常用的方法
    继承HttpServlet方法

    public class ServletDemo3 extends HttpServlet {

    @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("haha");

    }

    @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("ee");

    doGet(req,resp);

    }

    }

  • 相关阅读:
    Flink实例(四十七):状态管理(十一)自定义操作符状态(五)广播状态(Broadcast state)(三)
    Flink实例(四十六): Operators(七)多流转换算子(二)CONNECT, COMAP和COFLATMAP
    python题库
    python---replace函数
    算法图解--读书笔记
    python里的StringIO
    python通过sha1和base64生成签名
    python调用接口方式
    智能停车场车牌识别系统【python】
    leetcode 查找算法(三)
  • 原文地址:https://www.cnblogs.com/TangGe520/p/8980729.html
Copyright © 2011-2022 走看看