HttpServlet Source Code Analysis

Source: Internet
Author: User

1.HttpServletBrief introduction

HttpServletgenerates HTTP response results for the response based on the HTTP request made by the customer. HttpServlet must first read the contents of the HTTP request. The servlet container is responsible for creating the HttpRequest object and encapsulating the HTTP request information into the HttpRequestin the image, this greatly simplifies the effort of HttpServlet to parse the request data. If there is no httpservletrequest,httpservlet, only the original string data emitted by the Web client can be processed directly.

2.httpservlet Source Code Analysis

HttpServlet inherits Genericservlet. Genericservlet is an abstract class,HttpServlet is also an abstract class, but the support method for HTTP protocol is defined in HttpServlet. It defines the supported request methods, and the specific logic of the request processing.

the supported request methods are:

    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";
protected void Doget (HttpServletRequest req, HttpServletResponse resp) protected void Dohead (HttpServletRequest req, HttpServletResponse resp) protected void DoPost (HttpServletRequest req, HttpServletResponse resp) protected void DoPut ( HttpServletRequest req, HttpServletResponse resp) protected void DoDelete (HttpServletRequest req,httpservletresponse RESP) protected void dooptions (HttpServletRequest req,httpservletresponse resp) protected void Dotrace ( HttpServletRequest req, HttpServletResponse resp)

Specific processing logic (get as an example):

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

gets the HTTP protocol for the request first, or 405 if it is http1.1, otherwise returns 400. This is just a simple process, and all custom servlets generally inheritHttpServlet, overrides the processing logic of the request method . the parameters of the doget areHttpServletRequest andHttpServletResponse. HttpServletRequest contains the request information for HTTP, theHttpServletResponse contains the response information. (httpservletrequest,HttpServletResponse are created by the Web container.) )

In addition to the various protocols that process requests, there is a total method service that requests receive

public void Service (ServletRequest req, servletresponse Res)        throws Servletexception, IOException    {        HttpServletRequest  request;        HttpServletResponse response;                if (! ( Req instanceof httpservletrequest &&                res instanceof httpservletresponse) {            throw new servletexception ("Non-http Request or response");        }        Request = (httpservletrequest) req;        Response = (httpservletresponse) res;        Service (request, response);    }

called

protected void Service (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {        String method = Req.getmethod ();            if (Method.equals (Method_get)) {Long lastmodified = getlastmodified (req); if (lastmodified = =-1) {//servlet doesn ' t support if-modified-since, no reason//to go t            Hrough further expensive logic doget (req, resp);                } else {Long ifmodifiedsince = Req.getdateheader (header_ifmodsince);                    if (Ifmodifiedsince < lastmodified) {//If the servlet mod time is later, call Doget () Round down to the nearest second for a proper compare//a ifmodifiedsince of-1 would always                    is less maybesetlastmodified (resp, lastmodified);                Doget (req, resp); } else {Resp.setstatus (httpservletresponse.sc_not_modified);            }}} and Else if (Method.equals (Method_head)) {Long lastmodified = getlastmodified (req);            Maybesetlastmodified (resp, lastmodified);        Dohead (req, resp);                    } else if (Method.equals (method_post)) {DoPost (req, resp);                    } else if (Method.equals (method_put)) {DoPut (req, resp);                    } else if (Method.equals (Method_delete)) {DoDelete (req, resp);                    } else if (Method.equals (method_options)) {dooptions (REQ,RESP);                    } else if (Method.equals (Method_trace)) {dotrace (REQ,RESP);  } else {////Note This means NO Servlets supports whatever//method was requested,            Anywhere on the this server.            String errmsg = lstrings.getstring ("http.method_not_implemented");            object[] Errargs = new Object[1]; Errargs[0] = MetHod                        ErrMsg = Messageformat.format (errmsg, Errargs);        Resp.senderror (httpservletresponse.sc_not_implemented, errmsg); }    }

The visible request is distributed to the individual request method processing logic in the service according to the requested method.

Long lastmodified = getlastmodified (req);

here the protected method of this class is called: Getlastmodified

Protected long getlastmodified (HttpServletRequest req) {        return-1;    }

This method returns all-1. This method is related to caching. The specific logic is as follows:

in the HTTP protocol, after the browser has cached the page that has been accessed, it will later access the page The If-modified-since header field is generated based on the time value specified in the LastModified header field, as the most recent update time for the cached page. If the last modification time of the Web page is earlier than the time specified in the If-modified-since header field, the Web server will request a page, and if the page content has not been modified since the if-modified-since specified time, the server will return a 304 response header , telling the browser to continue using the cached page at once. After the servlet program that inherits the HttpServlet receives a GET request from the client, the overloaded service method of HttpServlet calls the Getlastmodified method first. Depending on the return value of this method, you decide whether you want to call the Doget method and generate the Last-modified header field. There are three main ways of deciding:

1. If the return value of the Getlastmodified method is a negative number, the service method calls the Doget method to generate the response information back to the client, regardless of the client's request information.

2. If the return value of the Getlastmodified method is a positive number and the client's request message does not contain a If-modified-since header field (in this case, when the page is first accessed) Or the request message contains the If-modified-since header field, but the return value is newer than the time specified in the If-modified-since header field, The service method calls the Doget method to generate the response information and the Last-modified message header is returned to the client.

3. If the return value of the Getlastmodified method is a positive number, and the return value is older than the time value specified in the If-modified-since header field in the request message issued by the client, The service method will not call the Doget method and generate the last-modified header , but instead returns a 304 state to the client, indicating that the client continues to use the previously cached page.
In addition, HttpServlet contains two classes: Nobodyresponse, Nobodyoutputstream. This two class is not a discussion.
HttpServlet Source Analysis to this.

HttpServlet Source Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.