JavaWeb學習之Servlet(二)----Servlet的生命週期、繼承結構、修改Servlet模板

 【聲明】html

歡迎轉載,但請保留文章原始出處→_→java

文章來源:http://www.cnblogs.com/smyhvae/p/4140466.htmlweb

 

1、http協議回顧:瀏覽器

在上一篇文章中:JavaWeb學習之Servlet(一)----MyEclipse及Tomcat的配置,咱們經過在瀏覽器輸入url,就能看到在MyEclipse中編寫的Servlet資源,效果以下:服務器

上圖中,整個過程是這樣的:瀏覽器中輸入url後,會經過hosts文件/dns服務器解析爲IP地址,進而找到對應ip地址的服務器。eclipse

在這期間,瀏覽器會經過http協議發出請求。服務器端收到請求後,作了下面這些事:ide

(1)分析出當前請求的是哪臺虛擬主機:工具

  • 查看Host請求頭分析出訪問的是哪臺虛擬主機
  • 若是沒有Host請求頭(在瀏覽器地址欄直接輸入ip地址而不是url),則訪問缺省虛擬主機

(2)分析當前請求訪問的是當前虛擬主機的哪一個Web應用:post

  • 從請求行中請求的資源部分來分析

(3)分析當前請求要訪問的是這個Web應用的哪一個資源:學習

  • 從請求行的資源部分分析出訪問的是哪一個資源

(4)查找web.xml文件,查看有沒有對應的虛擬路徑,若是有則用這個虛擬路徑對應的資源作響應

(5)服務器從response對象中獲取以前寫入的數據(這就是寫在Servlet當中的java代碼),組織成http響應消息發給瀏覽器

注:第(5)句話即是本文要學習的重點。

 

2、Servet的運行過程及生命週期

Servlet程序是由WEB服務器調用,web服務器收到客戶端的ServletWeb服務器首先檢查是否已經裝載並建立了該Servlet的實例對象。若是是,則直接執行第(4)步,不然,執行第(2)步。

訪問請求後:

(1)裝載並建立該Servlet的一個實例對象。

(2)調用Servlet實例對象的init()方法。

(3)建立一個用於封裝HTTP請求消息的HttpServletRequest對象和一個表明HTTP響應消息的HttpServletResponse對象,而後調用Servlet的service()方法並將請求和響應對象做爲參數傳遞進去。

(4)WEB應用程序被中止或從新啓動以前,Servlet引擎將卸載Servlet,並在卸載以前調用Servlet的destroy()方法。 

Servet的生命週期:

Servlet 的生命週期定義了一個Servlet如何被加載、初始化,以及它怎樣接收請求、響應請求、提供服務。

生命週期以下:

  • (1)一般狀況下,服務器會在Servlet第一次被調用時建立該Servlet類的實例對象(servlet出生),建立出對象後當即調用init()方法作初始化操做;
  • (2)一旦被建立出來,該Servlet實例就會駐留在內存中,爲後續對這個Servlet的請求作服務,每次對這個Servlet的訪問都會致使Servlet中Service方法執行;
  • (3)當web應用被移除容器或者關閉服務器時,隨着web應用的銷燬,Servlet也會被銷燬(servlet死亡)。在銷燬以前服務器會調用Servlet的destroy方法作一些善後的工做。

有3個方法表明了Servlet的生命週期:

  • init方法,負責初始化Servlet對象。
  • service方法,負責響應客戶的請求(調用doGet或doPost等方法)。
  • destroy方法,當Servlet對象退出生命週期時,負責釋放佔用的資源。

注:在Servlet的整個生命週期內,Servlet的init方法只有在servlet被建立時被調用一次,每次對這個Servlet的訪問都會致使Servlet中Service方法執行。

例如:如今瀏覽器連續訪問Servlet 10次,內存中只有一個Sevlet對象。Servlet對象由服務器建立(建立一次),request和response由Servlet容器建立(建立10次)

來看一段代碼:

 1 package com.vae.servlet;
 2 import java.io.IOException;
 3 import java.io.PrintWriter;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 //通常實現一個Servlet,只要繼承HttpServlet類便可
 9 public class MyServlet extends HttpServlet {
10     //Servlet初始化時調用的方法
11     @Override
12     public void init() throws ServletException {
13         super.init();
14         System.out.println("init....");
15     }
16     
17     //Servlet被銷燬時調用的方法
18     @Override
19     public void destroy() {
20         super.destroy();
21         System.out.println("destroy...");
22     }
23     //-------doGet/doPost 核心的業務處理方法(由service方法來調用)------------    
24     @Override
25     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
26             throws ServletException, IOException {
27         //super.doGet(req, resp);
28         doPost(req, resp);
29         System.out.println("do service...");
30     }
31     
32     @Override
33     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
34             throws ServletException, IOException {
35         //super.doPost(req, resp);
36     }
37 }

運行程序,輸入url,此時,一按回車,立刻就會在後臺打出日誌:

而後連續刷新三次網頁,日誌以下:

能夠看到,Servelet只會初始化一次,以後的話,咱們屢次訪問的是同一個Sevlet對象。此時,即便關掉網頁,Servlet也不會銷燬,只有關掉Tomcat服務器纔會銷燬Servlet。

須要注意的是,前臺可能有get和post兩種請求,可是在後臺作的處理是同樣的。例如:前臺輸入用戶名密碼,在後臺驗證的時候是不區分哪種請求方式的。因而,若是在doGet()方法中寫了代碼內容,咱們能夠在doPost()方法中加一句:"doGet(req,resp);"便可,就能夠進行重複利用(畢竟執行的都是同一段邏輯)。

 

3、Servlet的繼承結構:

  • Servlet接口:定義了Servlet應該具備的基本方法
  • GenericServlet:抽象類,實現了Servlet接口。通用基本Servlet實現,對於不經常使用的方法在這個實現類中進行了基本的實現,將Service設計爲了抽象方法,須要子類去實現
  • HttpServlet:抽象類,繼承了GenericServlet類。在通用Servlet的基礎上基於HTTP協議進行了進一步的強化:複寫了GenericServlet中的Service方法,Service方法體內的代碼會自動判斷用戶的請求方式如爲GET請求,則調用HttpServlet的doGet方法,如爲Post請求,則調用doPost方法。所以,開發人員在編寫Servlet時,一般只須要繼承HttpServlet,而後覆寫doGet或doPost方法,而不要去覆寫service方法。

 

4、修改Servlet模板:

使用MyEclipse建立Servlet時,根據默認的Servlet模板生成的Servlet代碼以下:

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 
10 public class Servlet2 extends HttpServlet {
11 
12     /**
13      * The doGet method of the servlet. <br>
14      *
15      * This method is called when a form has its tag value method equals to get.
16      * 
17      * @param request the request send by the client to the server
18      * @param response the response send by the server to the client
19      * @throws ServletException if an error occurred
20      * @throws IOException if an error occurred
21      */
22     public void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24 
25         response.setContentType("text/html");
26         PrintWriter out = response.getWriter();
27         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
28         out.println("<HTML>");
29         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
30         out.println("  <BODY>");
31         out.print("    This is ");
32         out.print(this.getClass());
33         out.println(", using the GET method");
34         out.println("  </BODY>");
35         out.println("</HTML>");
36         out.flush();
37         out.close();
38     }
39 
40     /**
41      * The doPost method of the servlet. <br>
42      *
43      * This method is called when a form has its tag value method equals to post.
44      * 
45      * @param request the request send by the client to the server
46      * @param response the response send by the server to the client
47      * @throws ServletException if an error occurred
48      * @throws IOException if an error occurred
49      */
50     public void doPost(HttpServletRequest request, HttpServletResponse response)
51             throws ServletException, IOException {
52 
53         response.setContentType("text/html");
54         PrintWriter out = response.getWriter();
55         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
56         out.println("<HTML>");
57         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
58         out.println("  <BODY>");
59         out.print("    This is ");
60         out.print(this.getClass());
61         out.println(", using the POST method");
62         out.println("  </BODY>");
63         out.println("</HTML>");
64         out.flush();
65         out.close();
66     }
67 
68 }
View Code

在實際開發中,這些生成的代碼和註釋通常咱們都用不到的,每次都要手工刪除這些註釋和代碼,很麻煩,所以能夠根據開發的實際狀況修改Servlet的模板代碼,改爲符合實際開發需求的模板代碼。

MyEclipse 10修改Servlet模板的步驟以下:

關閉MyEclipse,找到MyEclipse安裝目錄下的\Common\plugins文件夾,好比:D:\MyEclipse10\Common\plugins而後找到com.genuitec.eclipse.wizards_9.0.0.me201108091322.jar這個jar文件,以下圖所示:

950e08d3-2786-46f2-b234-6957a8923cd4

用壓縮工具打開,注意是打開而不是解壓這個jar包,以下圖所示:

aecc9f6c-e5df-4391-8a5d-66747007c630

5021689d-6f52-4709-aa1f-1cf8ecaab25f

上圖中,打開Jar包中的Templates文件夾中的Servlet.java文件,能夠看到裏面的模板代碼:

  1 #---------------------------------------------#
  2 # <aw:description>Template for Servlet</aw:description>
  3 # <aw:version>1.1</aw:version>
  4 # <aw:date>04/05/2003</aw:date>
  5 # <aw:author>Ferret Renaud</aw:author>
  6 #---------------------------------------------#
  7 
  8 <aw:import>java.io.IOException</aw:import>
  9 <aw:import>java.io.PrintWriter</aw:import>
 10 
 11 <aw:import>javax.servlet.ServletException</aw:import>
 12 <aw:import>javax.servlet.http.HttpServlet</aw:import>
 13 <aw:import>javax.servlet.http.HttpServletRequest</aw:import>
 14 <aw:import>javax.servlet.http.HttpServletResponse</aw:import>
 15 
 16 <aw:parentClass>javax.servlet.http.HttpServlet</aw:parentClass>
 17 
 18 <aw:constructor name="c1">
 19     /**
 20      * Constructor of the object.
 21      */
 22     public <aw:className/>() {
 23         super();
 24     }
 25 
 26 </aw:constructor> 
 27  
 28 <aw:method name="doGet">
 29     /**
 30      * The doGet method of the servlet. <br>
 31      *
 32      * This method is called when a form has its tag value method equals to get.
 33      * 
 34      * @param request the request send by the client to the server
 35      * @param response the response send by the server to the client
 36      * @throws ServletException if an error occurred
 37      * @throws IOException if an error occurred
 38      */
 39     public void doGet(HttpServletRequest request, HttpServletResponse response)
 40         throws ServletException, IOException {
 41         response.setContentType("text/html");
 42         PrintWriter out = response.getWriter();
 43         out.println(
 44             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 45         out.println("<HTML>");
 46         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 47         out.println("  <BODY>");
 48         out.print("    This is ");
 49         out.print(this.getClass());
 50         out.println(", using the GET method");
 51         out.println("  </BODY>");
 52         out.println("</HTML>");
 53         out.flush();
 54         out.close();
 55     }
 56 
 57 </aw:method>
 58 
 59 <aw:method name="doPost">
 60     /**
 61      * The doPost method of the servlet. <br>
 62      *
 63      * This method is called when a form has its tag value method equals to post.
 64      * 
 65      * @param request the request send by the client to the server
 66      * @param response the response send by the server to the client
 67      * @throws ServletException if an error occurred
 68      * @throws IOException if an error occurred
 69      */
 70     public void doPost(HttpServletRequest request, HttpServletResponse response)
 71         throws ServletException, IOException {
 72         response.setContentType("text/html");
 73         PrintWriter out = response.getWriter();
 74         out.println(
 75             "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 76         out.println("<HTML>");
 77         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 78         out.println("  <BODY>");
 79         out.print("    This is ");
 80         out.print(this.getClass());
 81         out.println(", using the POST method");
 82         out.println("  </BODY>");
 83         out.println("</HTML>");
 84         out.flush();
 85         out.close();
 86     }
 87 
 88 </aw:method>
 89 
 90 <aw:method name="doPut">
 91     /**
 92      * The doPut method of the servlet. <br>
 93      *
 94      * This method is called when a HTTP put request is received.
 95      * 
 96      * @param request the request send by the client to the server
 97      * @param response the response send by the server to the client
 98      * @throws ServletException if an error occurred
 99      * @throws IOException if an error occurred
100      */
101     public void doPut(HttpServletRequest request, HttpServletResponse response)
102         throws ServletException, IOException {
103 
104         // Put your code here
105 
106     }
107 
108 </aw:method>
109 
110 <aw:method name="doDelete">
111     /**
112      * The doDelete method of the servlet. <br>
113      *
114      * This method is called when a HTTP delete request is received.
115      * 
116      * @param request the request send by the client to the server
117      * @param response the response send by the server to the client
118      * @throws ServletException if an error occurred
119      * @throws IOException if an error occurred
120      */
121     public void doDelete(HttpServletRequest request, HttpServletResponse response)
122         throws ServletException, IOException {
123 
124         // Put your code here
125 
126     }
127 
128 </aw:method>
129 
130 <aw:method name="init">
131     /**
132      * Initialization of the servlet. <br>
133      *
134      * @throws ServletException if an error occurs
135      */
136     public void init() throws ServletException {
137         // Put your code here
138     }
139 
140 </aw:method>
141 
142 <aw:method name="destroy">
143     /**
144      * Destruction of the servlet. <br>
145      */
146     public void destroy() {
147         super.destroy(); // Just puts "destroy" string in log
148         // Put your code here
149     }
150 
151 </aw:method>
152 
153 <aw:method name="getServletInfo">
154     /**
155      * Returns information about the servlet, such as 
156      * author, version, and copyright. 
157      *
158      * @return String information about this servlet
159      */
160     public String getServletInfo() {
161         return "This is my default servlet created by Eclipse";
162     }
163 
164 </aw:method>
View Code

代碼模板中,刪除doGet和doPost上方的註釋和方法裏面的代碼,並在doPost方法裏面添加一doGet(request,response);效果以下:

f8373f28-9753-4e9b-9076-2393e323217a

修改好以後,保存,重啓MyEclipse,就可使用新的模板代碼了:

package com.vae.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Servlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
相關文章
相關標籤/搜索