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

    }

    }

  • 相关阅读:
    CentOS7 离线安装fastDFS、jdk1.8、mysql5.7、nginx、libreOffice
    java生成随机验证码
    Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContext
    js获取本地IP
    CentOS6.5下Oracle11.2安装
    IE浏览器不兼容indexOf问题
    有关LocalAlloc,LocalReAlloc,LocalFree,GlobalAlloc,GlobalReAlloc,GlobalFree的模糊点总结
    03UseTls
    03EventDemo
    lockFunctionDemo
  • 原文地址:https://www.cnblogs.com/TangGe520/p/8980729.html
Copyright © 2011-2022 走看看