HttpServlet Source Code Description

Source: Internet
Author: User
Tags http post

The previous article looked at the servlet interface, now look at the httpservlet we often involve:

/** * * provides an abstract class to being 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: * * <u l> * <li> <code>doget</code>, if the servlet supports HTTP GET requests * <li> <code>dopo St</code>, for HTTP POST requests * <li> <code>doput</code>, a for HTTP PUT requests * <li> &L T;code>dodelete</code>, for HTTP DELETE requests * <li> <code>init</code> and <code> DESTROY&LT;/CODE&GT, * To manage resources that is held for the life of the servlet * <li> <code>getservlet  Info</code&gt, 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 handlerMethods * 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 &LT;CODE&GT;DOTR Ace</code> methods. * * <p>servlets typically run on multithreaded servers, * So is aware that a servlet must handle concurrent * Reque STS and is 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, data Base 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. * * @authorVarious*/ Public Abstract classHttpServletextendsGenericservletImplementsjava.io.serializable{Private Static FinalString method_delete = "DELETE"; Private Static FinalString method_head = "HEAD"; Private Static FinalString method_get = "GET"; Private Static FinalString method_options = "OPTIONS"; Private Static FinalString method_post = "POST"; Private Static FinalString method_put = "PUT"; Private Static FinalString method_trace = "TRACE"; Private Static FinalString header_ifmodsince = "If-modified-since"; Private Static FinalString header_lastmod = "Last-modified"; Private Static FinalString lstring_file = "Javax.servlet.http.LocalStrings"; Private StaticResourceBundle lstrings =Resourcebundle.getbundle (Lstring_file); 

HttpServlet is an abstract class, which is a servlet for implementing the HTTP protocol, and all servlets that inherit this abstract class must implement one of the following methods:

Doget;

DoPost;

DoPut;

DoDelete;

Init and destroy;

There is no need to rewrite the service method, service processing standard HTTP requests, according to different HTTP request types distributed to the above doxxx method for processing;

The other description is the same as in the previous one, where there is no more space.

Here's a look at the Doget method and the Dopost method:

1, Doget:

    /**     * * Called by the server (via the <code>service</code> method) to * allow a servlet to handle a G      ET request. * * <p>overriding This method to the support a GET request also * automatically supports an HTTP HEAD request.     A HEAD * request is a GET request of 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 a     Ccessing the * <code>PrintWriter</code> object. * * <p>the servlet container must write the headers before * committing the response, because in HTTP the He     Aders 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 connect     Ion * To return it 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 * have a transfer-encoding header)     , do not set the Content-length header. * * <p>the GET method should be safe, that's, without * any side effects for which users are held Responsib     Le.     * For example, the most form queries has 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 * This 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 a HTTP "bad reques     T "message.  *      *     *@paramreq an {@linkHttpServletRequest} object that * contains the request the client has made * of the SER Vlet * *@paramresp an {@linkHttpServletResponse} object that * Contains the response the servlet sends * to the CLI ENT * *@exceptionIOException If an input or output error was * detected when the servlet handles * The GET request * *@exceptionServletexception If the request for the GET * could not being handled * * *@seeJavax.servlet.servletresponse#setcontenttype **/    protected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, 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); }    }

^ This method is called by the server to allow a servlet to process a GET request;

^ Override this method to support a GET request while also supporting a head request, a head request is a GET request that does not return any principal in response, only the request header field;

^ When loading this method, read the request data, write to the response header, get response writer object or output stream object, finally write response data, preferably include content type and encoding method;

The ^servlet container must write the header file before committing the response because the file header must be submitted before the response body in the HTTP protocol;

The ^set method is secure, meaning that the method does not have any side effects that require user responsibility, such as: Most queries have no side effects, and you need to use other methods when you try to change the database data. This means that the Get method is only used to query some simple data;

2, Dopost Method:

  /**       * * Called by the server (via the <code>service</code> method) * To allow a servlet to handle a P     OST 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 He     Aders must be sent before the * response body. * * <p>where possible, set the COntent-length header (with the * { @linkJavax.servlet.servletresponse#setcontentlength} method), * to allow the servlet container to use a persistent con     Nection * To return it 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 * have 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 is 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. *     *     * @paramreq an {@linkHttpServletRequest} object that * contains the request the client has made * of the SER Vlet * *@paramresp an {@linkHttpServletResponse} object that * Contains the response the servlet sends * to the CLI ENT * *@exceptionIOException If an input or output error was * detected when the servlet handles * The request * *@exceptionServletexception If the request for the POST * could not being handled * * *@seeJavax.servlet.ServletOutputStream *@seeJavax.servlet.servletresponse#setcontenttype * **/    protected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, 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); }    }

At this point you will find a very similar description of the Doget method above. The only difference is that Dopost handles requests to modify data.

The other four ways I do not enumerate, the same, we look at it.

HttpServlet Source Code Description

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.