關(guān)于servlet的創(chuàng)建,我們有三種方式。
我們先來看第一種,實(shí)現(xiàn)Servlet接口。
因?yàn)槭菍?shí)現(xiàn)servlet接口,所以我們需要實(shí)現(xiàn)接口里的方法。
下面我們也說明了servlet的執(zhí)行過程,也就是servlet的生命周期。
//Servlet的生命周期:從Servlet被創(chuàng)建到Servlet被銷毀的過程//一次創(chuàng)建,到處服務(wù)//一個(gè)Servlet只會(huì)有一個(gè)對(duì)象,服務(wù)所有的請(qǐng)求/* * 1.實(shí)例化(使用構(gòu)造方法創(chuàng)建對(duì)象) * 2.初始化 執(zhí)行init方法 * 3.服務(wù) 執(zhí)行service方法 * 4.銷毀 執(zhí)行destroy方法 */public class ServletDemo1 implements Servlet { //public ServletDemo1(){} //生命周期方法:當(dāng)Servlet第一次被創(chuàng)建對(duì)象時(shí)執(zhí)行該方法,該方法在整個(gè)生命周期中只執(zhí)行一次 public void init(ServletConfig arg0) throws ServletException { System.out.println("=======init========="); } //生命周期方法:對(duì)客戶端響應(yīng)的方法,該方法會(huì)被執(zhí)行多次,每次請(qǐng)求該servlet都會(huì)執(zhí)行該方法 public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { System.out.println("hehe"); } //生命周期方法:當(dāng)Servlet被銷毀時(shí)執(zhí)行該方法 public void destroy() { System.out.println("******destroy**********"); }//當(dāng)停止tomcat時(shí)也就銷毀的servlet。 public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; }}
public class ServletDemo2 extends GenericServlet { @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { System.out.println("heihei"); }}
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); }}
聯(lián)系客服