Httpservlet源碼說明

來源:互聯網
上載者:User

標籤:

上一篇看了Servlet介面,現在來看下我們經常涉及的Httpservlet:

/** * * Provides an abstract class to be subclassed to create * an HTTP servlet suitable for a Web site. A subclass of * <code>HttpServlet</code> must override at least  * one method, usually one of these: * * <ul> * <li> <code>doGet</code>, if the servlet supports HTTP GET requests * <li> <code>doPost</code>, for HTTP POST requests * <li> <code>doPut</code>, for HTTP PUT requests * <li> <code>doDelete</code>, for HTTP DELETE requests * <li> <code>init</code> and <code>destroy</code>,  * to manage resources that are held for the life of the servlet * <li> <code>getServletInfo</code>, which the servlet uses to * provide information about itself  * </ul> * * <p>There‘s almost no reason to override the <code>service</code> * method. <code>service</code> handles standard HTTP * requests by dispatching them to the handler methods * for each HTTP request type (the <code>do</code><i>XXX</i> * methods listed above). * * <p>Likewise, there‘s almost no reason to override the  * <code>doOptions</code> and <code>doTrace</code> methods. *  * <p>Servlets typically run on multithreaded servers, * so be aware that a servlet must handle concurrent * requests and be careful to synchronize access to shared resources. * Shared resources include in-memory data such as * instance or class variables and external objects * such as files, database connections, and network  * connections. * See the * <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> * Java Tutorial on Multithreaded Programming</a> for more * information on handling multiple threads in a Java program. * * @author    Various */public abstract class HttpServlet extends GenericServlet    implements java.io.Serializable{    private static final String METHOD_DELETE = "DELETE";    private static final String METHOD_HEAD = "HEAD";    private static final String METHOD_GET = "GET";    private static final String METHOD_OPTIONS = "OPTIONS";    private static final String METHOD_POST = "POST";    private static final String METHOD_PUT = "PUT";    private static final String METHOD_TRACE = "TRACE";    private static final String HEADER_IFMODSINCE = "If-Modified-Since";    private static final String HEADER_LASTMOD = "Last-Modified";        private static final String LSTRING_FILE =    "javax.servlet.http.LocalStrings";    private static ResourceBundle lStrings =    ResourceBundle.getBundle(LSTRING_FILE);      

HttpServlet是一個抽象類別,它是為了實現http協議的servlet,所有繼承此抽象類別的servlet必須實現以下方法中的一種:

doGet;

doPost;

doPut;

doDelete;

init 和 destroy;

沒有必要去重寫service方法,service處理標準的http請求,根據不同的HTTP請求類型分發給以上的doXXX方法進行處理;

其他的描述和上一篇的servlet一樣,在此就不多費篇幅咯。

下面重點看看doGet方法和doPost方法:

1、doGet:

    /**     *     * Called by the server (via the <code>service</code> method) to     * allow a servlet to handle a GET request.      *     * <p>Overriding this method to support a GET request also     * automatically supports an HTTP HEAD request. A HEAD     * request is a GET request that returns no body in the     * response, only the request header fields.     *     * <p>When overriding this method, read the request data,     * write the response headers, get the response‘s writer or      * output stream object, and finally, write the response data.     * It‘s best to include content type and encoding. When using     * a <code>PrintWriter</code> object to return the response,     * set the content type before accessing the     * <code>PrintWriter</code> object.     *     * <p>The servlet container must write the headers before     * committing the response, because in HTTP the headers must be sent     * before the response body.     *     * <p>Where possible, set the Content-Length header (with the     * {@link javax.servlet.ServletResponse#setContentLength} method),     * to allow the servlet container to use a persistent connection      * to return its response to the client, improving performance.     * The content length is automatically set if the entire response fits     * inside the response buffer.     *     * <p>When using HTTP 1.1 chunked encoding (which means that the response     * has a Transfer-Encoding header), do not set the Content-Length header.     *     * <p>The GET method should be safe, that is, without     * any side effects for which users are held responsible.     * For example, most form queries have no side effects.     * If a client request is intended to change stored data,     * the request should use some other HTTP method.     *     * <p>The GET method should also be idempotent, meaning     * that it can be safely repeated. Sometimes making a     * method safe also makes it idempotent. For example,      * repeating queries is both safe and idempotent, but     * buying a product online or modifying data is neither     * safe nor idempotent.      *     * <p>If the request is incorrectly formatted, <code>doGet</code>     * returns an HTTP "Bad Request" message.     *      *     * @param req    an {@link HttpServletRequest} object that     *            contains the request the client has made     *            of the servlet     *     * @param resp    an {@link HttpServletResponse} object that     *            contains the response the servlet sends     *            to the client     *      * @exception IOException    if an input or output error is      *                detected when the servlet handles     *                the GET request     *     * @exception ServletException    if the request for the GET     *                    could not be handled     *     *      * @see javax.servlet.ServletResponse#setContentType     *     */    protected void doGet(HttpServletRequest req, HttpServletResponse resp)    throws ServletException, IOException    {    String protocol = req.getProtocol();    String msg = lStrings.getString("http.method_get_not_supported");    if (protocol.endsWith("1.1")) {        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);    } else {        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);    }    }

^此方法由伺服器調用允許一個servlet去處理一個GET請求;

^重寫此方法去支援一個GET請求,同時也支援一個HEAD請求,一個HEAD請求是一個得到響應中沒有返回任何主體的GET請求,只有要求標頭欄位;

^當載入此方法時,讀取請求資料,寫入回應標頭,擷取response的writer對象或者輸出資料流對象,最終寫入response資料,最好包含內容類型和編碼方式;

^servlet容器必須在提交response之前寫標頭檔,因為在HTTP協議中檔案頭必須在response body體之前提交;

^set方法是安全的,也就是說這個方法沒有任何需要使用者負責任的副作用;比如:大多數的查詢都沒有副作用,當你試圖改變資料庫的資料時,則需要使用其他方法。也就是說GET方法只用於查詢某些簡單的資料;

 

2、doPost方法:

  /**     *     * Called by the server (via the <code>service</code> method)     * to allow a servlet to handle a POST request.     *     * The HTTP POST method allows the client to send     * data of unlimited length to the Web server a single time     * and is useful when posting information such as     * credit card numbers.     *     * <p>When overriding this method, read the request data,     * write the response headers, get the response‘s writer or output     * stream object, and finally, write the response data. It‘s best      * to include content type and encoding. When using a     * <code>PrintWriter</code> object to return the response, set the      * content type before accessing the <code>PrintWriter</code> object.      *     * <p>The servlet container must write the headers before committing the     * response, because in HTTP the headers must be sent before the      * response body.     *     * <p>Where possible, set the Content-Length header (with the     * {@link javax.servlet.ServletResponse#setContentLength} method),     * to allow the servlet container to use a persistent connection      * to return its response to the client, improving performance.     * The content length is automatically set if the entire response fits     * inside the response buffer.       *     * <p>When using HTTP 1.1 chunked encoding (which means that the response     * has a Transfer-Encoding header), do not set the Content-Length header.      *     * <p>This method does not need to be either safe or idempotent.     * Operations requested through POST can have side effects for     * which the user can be held accountable, for example,      * updating stored data or buying items online.     *     * <p>If the HTTP POST request is incorrectly formatted,     * <code>doPost</code> returns an HTTP "Bad Request" message.     *     *     * @param req    an {@link HttpServletRequest} object that     *            contains the request the client has made     *            of the servlet     *     * @param resp    an {@link HttpServletResponse} object that     *            contains the response the servlet sends     *            to the client     *      * @exception IOException    if an input or output error is      *                detected when the servlet handles     *                the request     *     * @exception ServletException    if the request for the POST     *                    could not be handled     *     *     * @see javax.servlet.ServletOutputStream     * @see javax.servlet.ServletResponse#setContentType     *     *     */    protected void doPost(HttpServletRequest req, HttpServletResponse resp)    throws ServletException, IOException    {    String protocol = req.getProtocol();    String msg = lStrings.getString("http.method_post_not_supported");    if (protocol.endsWith("1.1")) {        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);    } else {        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);    }    }

此時你會發現與上面的doGet方法的描述非常類似。唯一的不同是doPost會處理修改資料的請求。

其他的四種方法我就不一一列舉了,大同小異,大家自己看一下。

 

Httpservlet源碼說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.