httpServlet,GenericServlet,Servlet源码分析

简介: httpServlet源码:  [java] view plain copy /*  * Licensed to the Apache Software Foundation (ASF) under one or more  * contributor license agreements.

httpServlet源码:

 

 

[java]  view plain  copy
 
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  * 
  9.  *     http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17. package javax.servlet.http;  
  18.   
  19. import java.io.IOException;  
  20. import java.io.OutputStreamWriter;  
  21. import java.io.PrintWriter;  
  22. import java.io.UnsupportedEncodingException;  
  23. import java.lang.reflect.Method;  
  24. import java.text.MessageFormat;  
  25. import java.util.Enumeration;  
  26. import java.util.ResourceBundle;  
  27.   
  28. import javax.servlet.DispatcherType;  
  29. import javax.servlet.GenericServlet;  
  30. import javax.servlet.ServletException;  
  31. import javax.servlet.ServletOutputStream;  
  32. import javax.servlet.ServletRequest;  
  33. import javax.servlet.ServletResponse;  
  34.   
  35.   
  36. /** 
  37.  * Provides an abstract class to be subclassed to create 
  38.  * an HTTP servlet suitable for a Web site. A subclass of 
  39.  * <code>HttpServlet</code> must override at least 
  40.  * one method, usually one of these: 
  41.  * 
  42.  * <ul> 
  43.  * <li> <code>doGet</code>, if the servlet supports HTTP GET requests 
  44.  * <li> <code>doPost</code>, for HTTP POST requests 
  45.  * <li> <code>doPut</code>, for HTTP PUT requests 
  46.  * <li> <code>doDelete</code>, for HTTP DELETE requests 
  47.  * <li> <code>init</code> and <code>destroy</code>, 
  48.  * to manage resources that are held for the life of the servlet 
  49.  * <li> <code>getServletInfo</code>, which the servlet uses to 
  50.  * provide information about itself 
  51.  * </ul> 
  52.  * 
  53.  * <p>There's almost no reason to override the <code>service</code> 
  54.  * method. <code>service</code> handles standard HTTP 
  55.  * requests by dispatching them to the handler methods 
  56.  * for each HTTP request type (the <code>do</code><i>Method</i> 
  57.  * methods listed above). 
  58.  * 
  59.  * <p>Likewise, there's almost no reason to override the 
  60.  * <code>doOptions</code> and <code>doTrace</code> methods. 
  61.  * 
  62.  * <p>Servlets typically run on multithreaded servers, 
  63.  * so be aware that a servlet must handle concurrent 
  64.  * requests and be careful to synchronize access to shared resources. 
  65.  * Shared resources include in-memory data such as 
  66.  * instance or class variables and external objects 
  67.  * such as files, database connections, and network 
  68.  * connections. 
  69.  * See the 
  70.  * <a href="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> 
  71.  * Java Tutorial on Multithreaded Programming</a> for more 
  72.  * information on handling multiple threads in a Java program. 
  73.  */  
  74. public abstract class HttpServlet extends GenericServlet {  
  75.   
  76.     private static final long serialVersionUID = 1L;  
  77.   
  78.     private static final String METHOD_DELETE = "DELETE";  
  79.     private static final String METHOD_HEAD = "HEAD";  
  80.     private static final String METHOD_GET = "GET";  
  81.     private static final String METHOD_OPTIONS = "OPTIONS";  
  82.     private static final String METHOD_POST = "POST";  
  83.     private static final String METHOD_PUT = "PUT";  
  84.     private static final String METHOD_TRACE = "TRACE";  
  85.   
  86.     private static final String HEADER_IFMODSINCE = "If-Modified-Since";  
  87.     private static final String HEADER_LASTMOD = "Last-Modified";  
  88.   
  89.     private static final String LSTRING_FILE =  
  90.         "javax.servlet.http.LocalStrings";  
  91.     private static final ResourceBundle lStrings =  
  92.         ResourceBundle.getBundle(LSTRING_FILE);  
  93.   
  94.   
  95.     /** 
  96.      * Does nothing, because this is an abstract class. 
  97.      */  
  98.     public HttpServlet() {  
  99.         // NOOP  
  100.     }  
  101.   
  102.   
  103.     /** 
  104.      * Called by the server (via the <code>service</code> method) to 
  105.      * allow a servlet to handle a GET request. 
  106.      * 
  107.      * <p>Overriding this method to support a GET request also 
  108.      * automatically supports an HTTP HEAD request. A HEAD 
  109.      * request is a GET request that returns no body in the 
  110.      * response, only the request header fields. 
  111.      * 
  112.      * <p>When overriding this method, read the request data, 
  113.      * write the response headers, get the response's writer or 
  114.      * output stream object, and finally, write the response data. 
  115.      * It's best to include content type and encoding. When using 
  116.      * a <code>PrintWriter</code> object to return the response, 
  117.      * set the content type before accessing the 
  118.      * <code>PrintWriter</code> object. 
  119.      * 
  120.      * <p>The servlet container must write the headers before 
  121.      * committing the response, because in HTTP the headers must be sent 
  122.      * before the response body. 
  123.      * 
  124.      * <p>Where possible, set the Content-Length header (with the 
  125.      * {@link javax.servlet.ServletResponse#setContentLength} method), 
  126.      * to allow the servlet container to use a persistent connection 
  127.      * to return its response to the client, improving performance. 
  128.      * The content length is automatically set if the entire response fits 
  129.      * inside the response buffer. 
  130.      * 
  131.      * <p>When using HTTP 1.1 chunked encoding (which means that the response 
  132.      * has a Transfer-Encoding header), do not set the Content-Length header. 
  133.      * 
  134.      * <p>The GET method should be safe, that is, without 
  135.      * any side effects for which users are held responsible. 
  136.      * For example, most form queries have no side effects. 
  137.      * If a client request is intended to change stored data, 
  138.      * the request should use some other HTTP method. 
  139.      * 
  140.      * <p>The GET method should also be idempotent, meaning 
  141.      * that it can be safely repeated. Sometimes making a 
  142.      * method safe also makes it idempotent. For example, 
  143.      * repeating queries is both safe and idempotent, but 
  144.      * buying a product online or modifying data is neither 
  145.      * safe nor idempotent. 
  146.      * 
  147.      * <p>If the request is incorrectly formatted, <code>doGet</code> 
  148.      * returns an HTTP "Bad Request" message. 
  149.      * 
  150.      * @param req   an {@link HttpServletRequest} object that 
  151.      *                  contains the request the client has made 
  152.      *                  of the servlet 
  153.      * 
  154.      * @param resp  an {@link HttpServletResponse} object that 
  155.      *                  contains the response the servlet sends 
  156.      *                  to the client 
  157.      * 
  158.      * @exception IOException   if an input or output error is 
  159.      *                              detected when the servlet handles 
  160.      *                              the GET request 
  161.      * 
  162.      * @exception ServletException  if the request for the GET 
  163.      *                                  could not be handled 
  164.      * 
  165.      * @see javax.servlet.ServletResponse#setContentType 
  166.      */  
  167.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  168.         throws ServletException, IOException  
  169.     {  
  170.         String protocol = req.getProtocol();  
  171.         String msg = lStrings.getString("http.method_get_not_supported");  
  172.         if (protocol.endsWith("1.1")) {  
  173.             resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);  
  174.         } else {  
  175.             resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);  
  176.         }  
  177.     }  
  178.   
  179.   
  180.     /** 
  181.      * Returns the time the <code>HttpServletRequest</code> 
  182.      * object was last modified, 
  183.      * in milliseconds since midnight January 1, 1970 GMT. 
  184.      * If the time is unknown, this method returns a negative 
  185.      * number (the default). 
  186.      * 
  187.      * <p>Servlets that support HTTP GET requests and can quickly determine 
  188.      * their last modification time should override this method. 
  189.      * This makes browser and proxy caches work more effectively, 
  190.      * reducing the load on server and network resources. 
  191.      * 
  192.      * @param req   the <code>HttpServletRequest</code> 
  193.      *                  object that is sent to the servlet 
  194.      * 
  195.      * @return  a <code>long</code> integer specifying 
  196.      *              the time the <code>HttpServletRequest</code> 
  197.      *              object was last modified, in milliseconds 
  198.      *              since midnight, January 1, 1970 GMT, or 
  199.      *              -1 if the time is not known 
  200.      */  
  201.     protected long getLastModified(HttpServletRequest req) {  
  202.         return -1;  
  203.     }  
  204.   
  205.   
  206.     /** 
  207.      * <p>Receives an HTTP HEAD request from the protected 
  208.      * <code>service</code> method and handles the 
  209.      * request. 
  210.      * The client sends a HEAD request when it wants 
  211.      * to see only the headers of a response, such as 
  212.      * Content-Type or Content-Length. The HTTP HEAD 
  213.      * method counts the output bytes in the response 
  214.      * to set the Content-Length header accurately. 
  215.      * 
  216.      * <p>If you override this method, you can avoid computing 
  217.      * the response body and just set the response headers 
  218.      * directly to improve performance. Make sure that the 
  219.      * <code>doHead</code> method you write is both safe 
  220.      * and idempotent (that is, protects itself from being 
  221.      * called multiple times for one HTTP HEAD request). 
  222.      * 
  223.      * <p>If the HTTP HEAD request is incorrectly formatted, 
  224.      * <code>doHead</code> returns an HTTP "Bad Request" 
  225.      * message. 
  226.      * 
  227.      * @param req   the request object that is passed to the servlet 
  228.      * 
  229.      * @param resp  the response object that the servlet 
  230.      *                  uses to return the headers to the client 
  231.      * 
  232.      * @exception IOException   if an input or output error occurs 
  233.      * 
  234.      * @exception ServletException  if the request for the HEAD 
  235.      *                                  could not be handled 
  236.      */  
  237.     protected void doHead(HttpServletRequest req, HttpServletResponse resp)  
  238.         throws ServletException, IOException {  
  239.   
  240.         if (DispatcherType.INCLUDE.equals(req.getDispatcherType())) {  
  241.             doGet(req, resp);  
  242.         } else {  
  243.             NoBodyResponse response = new NoBodyResponse(resp);  
  244.             doGet(req, response);  
  245.             response.setContentLength();  
  246.         }  
  247.     }  
  248.   
  249.   
  250.     /** 
  251.      * Called by the server (via the <code>service</code> method) 
  252.      * to allow a servlet to handle a POST request. 
  253.      * 
  254.      * The HTTP POST method allows the client to send 
  255.      * data of unlimited length to the Web server a single time 
  256.      * and is useful when posting information such as 
  257.      * credit card numbers. 
  258.      * 
  259.      * <p>When overriding this method, read the request data, 
  260.      * write the response headers, get the response's writer or output 
  261.      * stream object, and finally, write the response data. It's best 
  262.      * to include content type and encoding. When using a 
  263.      * <code>PrintWriter</code> object to return the response, set the 
  264.      * content type before accessing the <code>PrintWriter</code> object. 
  265.      * 
  266.      * <p>The servlet container must write the headers before committing the 
  267.      * response, because in HTTP the headers must be sent before the 
  268.      * response body. 
  269.      * 
  270.      * <p>Where possible, set the Content-Length header (with the 
  271.      * {@link javax.servlet.ServletResponse#setContentLength} method), 
  272.      * to allow the servlet container to use a persistent connection 
  273.      * to return its response to the client, improving performance. 
  274.      * The content length is automatically set if the entire response fits 
  275.      * inside the response buffer. 
  276.      * 
  277.      * <p>When using HTTP 1.1 chunked encoding (which means that the response 
  278.      * has a Transfer-Encoding header), do not set the Content-Length header. 
  279.      * 
  280.      * <p>This method does not need to be either safe or idempotent. 
  281.      * Operations requested through POST can have side effects for 
  282.      * which the user can be held accountable, for example, 
  283.      * updating stored data or buying items online. 
  284.      * 
  285.      * <p>If the HTTP POST request is incorrectly formatted, 
  286.      * <code>doPost</code> returns an HTTP "Bad Request" message. 
  287.      * 
  288.      * 
  289.      * @param req   an {@link HttpServletRequest} object that 
  290.      *                  contains the request the client has made 
  291.      *                  of the servlet 
  292.      * 
  293.      * @param resp  an {@link HttpServletResponse} object that 
  294.      *                  contains the response the servlet sends 
  295.      *                  to the client 
  296.      * 
  297.      * @exception IOException   if an input or output error is 
  298.      *                              detected when the servlet handles 
  299.      *                              the request 
  300.      * 
  301.      * @exception ServletException  if the request for the POST 
  302.      *                                  could not be handled 
  303.      * 
  304.      * @see javax.servlet.ServletOutputStream 
  305.      * @see javax.servlet.ServletResponse#setContentType 
  306.      */  
  307.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  308.         throws ServletException, IOException {  
  309.   
  310.         String protocol = req.getProtocol();  
  311.         String msg = lStrings.getString("http.method_post_not_supported");  
  312.         if (protocol.endsWith("1.1")) {  
  313.             resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);  
  314.         } else {  
  315.             resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);  
  316.         }  
  317.     }  
  318.   
  319.   
  320.     /** 
  321.      * Called by the server (via the <code>service</code> method) 
  322.      * to allow a servlet to handle a PUT request. 
  323.      * 
  324.      * The PUT operation allows a client to 
  325.      * place a file on the server and is similar to 
  326.      * sending a file by FTP. 
  327.      * 
  328.      * <p>When overriding this method, leave intact 
  329.      * any content headers sent with the request (including 
  330.      * Content-Length, Content-Type, Content-Transfer-Encoding, 
  331.      * Content-Encoding, Content-Base, Content-Language, Content-Location, 
  332.      * Content-MD5, and Content-Range). If your method cannot 
  333.      * handle a content header, it must issue an error message 
  334.      * (HTTP 501 - Not Implemented) and discard the request. 
  335.      * For more information on HTTP 1.1, see RFC 2616 
  336.      * <a href="http://www.ietf.org/rfc/rfc2616.txt"></a>. 
  337.      * 
  338.      * <p>This method does not need to be either safe or idempotent. 
  339.      * Operations that <code>doPut</code> performs can have side 
  340.      * effects for which the user can be held accountable. When using 
  341.      * this method, it may be useful to save a copy of the 
  342.      * affected URL in temporary storage. 
  343.      * 
  344.      * <p>If the HTTP PUT request is incorrectly formatted, 
  345.      * <code>doPut</code> returns an HTTP "Bad Request" message. 
  346.      * 
  347.      * @param req   the {@link HttpServletRequest} object that 
  348.      *                  contains the request the client made of 
  349.      *                  the servlet 
  350.      * 
  351.      * @param resp  the {@link HttpServletResponse} object that 
  352.      *                  contains the response the servlet returns 
  353.      *                  to the client 
  354.      * 
  355.      * @exception IOException   if an input or output error occurs 
  356.      *                              while the servlet is handling the 
  357.      *                              PUT request 
  358.      * 
  359.      * @exception ServletException  if the request for the PUT 
  360.      *                                  cannot be handled 
  361.      */  
  362.     protected void doPut(HttpServletRequest req, HttpServletResponse resp)  
  363.         throws ServletException, IOException {  
  364.   
  365.         String protocol = req.getProtocol();  
  366.         String msg = lStrings.getString("http.method_put_not_supported");  
  367.         if (protocol.endsWith("1.1")) {  
  368.             resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);  
  369.         } else {  
  370.             resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);  
  371.         }  
  372.     }  
  373.   
  374.   
  375.     /** 
  376.      * Called by the server (via the <code>service</code> method) 
  377.      * to allow a servlet to handle a DELETE request. 
  378.      * 
  379.      * The DELETE operation allows a client to remove a document 
  380.      * or Web page from the server. 
  381.      * 
  382.      * <p>This method does not need to be either safe 
  383.      * or idempotent. Operations requested through 
  384.      * DELETE can have side effects for which users 
  385.      * can be held accountable. When using 
  386.      * this method, it may be useful to save a copy of the 
  387.      * affected URL in temporary storage. 
  388.      * 
  389.      * <p>If the HTTP DELETE request is incorrectly formatted, 
  390.      * <code>doDelete</code> returns an HTTP "Bad Request" 
  391.      * message. 
  392.      * 
  393.      * @param req   the {@link HttpServletRequest} object that 
  394.      *                  contains the request the client made of 
  395.      *                  the servlet 
  396.      * 
  397.      * 
  398.      * @param resp  the {@link HttpServletResponse} object that 
  399.      *                  contains the response the servlet returns 
  400.      *                  to the client 
  401.      * 
  402.      * @exception IOException   if an input or output error occurs 
  403.      *                              while the servlet is handling the 
  404.      *                              DELETE request 
  405.      * 
  406.      * @exception ServletException  if the request for the 
  407.      *                                  DELETE cannot be handled 
  408.      */  
  409.     protected void doDelete(HttpServletRequest req,  
  410.                             HttpServletResponse resp)  
  411.         throws ServletException, IOException {  
  412.   
  413.         String protocol = req.getProtocol();  
  414.         String msg = lStrings.getString("http.method_delete_not_supported");  
  415.         if (protocol.endsWith("1.1")) {  
  416.             resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);  
  417.         } else {  
  418.             resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);  
  419.         }  
  420.     }  
  421.   
  422.   
  423.     private static Method[] getAllDeclaredMethods(Class<?> c) {  
  424.   
  425.         if (c.equals(javax.servlet.http.HttpServlet.class)) {  
  426.             return null;  
  427.         }  
  428.   
  429.         Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());  
  430.         Method[] thisMethods = c.getDeclaredMethods();  
  431.   
  432.         if ((parentMethods != null) && (parentMethods.length > 0)) {  
  433.             Method[] allMethods =  
  434.                 new Method[parentMethods.length + thisMethods.length];  
  435.             System.arraycopy(parentMethods, 0, allMethods, 0,  
  436.                              parentMethods.length);  
  437.             System.arraycopy(thisMethods, 0, allMethods, parentMethods.length,  
  438.                              thisMethods.length);  
  439.   
  440.             thisMethods = allMethods;  
  441.         }  
  442.   
  443.         return thisMethods;  
  444.     }  
  445.   
  446.   
  447.     /** 
  448.      * Called by the server (via the <code>service</code> method) 
  449.      * to allow a servlet to handle a OPTIONS request. 
  450.      * 
  451.      * The OPTIONS request determines which HTTP methods 
  452.      * the server supports and 
  453.      * returns an appropriate header. For example, if a servlet 
  454.      * overrides <code>doGet</code>, this method returns the 
  455.      * following header: 
  456.      * 
  457.      * <p><code>Allow: GET, HEAD, TRACE, OPTIONS</code> 
  458.      * 
  459.      * <p>There's no need to override this method unless the 
  460.      * servlet implements new HTTP methods, beyond those 
  461.      * implemented by HTTP 1.1. 
  462.      * 
  463.      * @param req   the {@link HttpServletRequest} object that 
  464.      *                  contains the request the client made of 
  465.      *                  the servlet 
  466.      * 
  467.      * @param resp  the {@link HttpServletResponse} object that 
  468.      *                  contains the response the servlet returns 
  469.      *                  to the client 
  470.      * 
  471.      * @exception IOException   if an input or output error occurs 
  472.      *                              while the servlet is handling the 
  473.      *                              OPTIONS request 
  474.      * 
  475.      * @exception ServletException  if the request for the 
  476.      *                                  OPTIONS cannot be handled 
  477.      */  
  478.     protected void doOptions(HttpServletRequest req,  
  479.             HttpServletResponse resp)  
  480.         throws ServletException, IOException {  
  481.   
  482.         Method[] methods = getAllDeclaredMethods(this.getClass());  
  483.   
  484.         boolean ALLOW_GET = false;  
  485.         boolean ALLOW_HEAD = false;  
  486.         boolean ALLOW_POST = false;  
  487.         boolean ALLOW_PUT = false;  
  488.         boolean ALLOW_DELETE = false;  
  489.         boolean ALLOW_TRACE = true;  
  490.         boolean ALLOW_OPTIONS = true;  
  491.   
  492.         for (int i=0; i<methods.length; i++) {  
  493.             Method m = methods[i];  
  494.   
  495.             if (m.getName().equals("doGet")) {  
  496.                 ALLOW_GET = true;  
  497.                 ALLOW_HEAD = true;  
  498.             }  
  499.             if (m.getName().equals("doPost"))  
  500.                 ALLOW_POST = true;  
  501.             if (m.getName().equals("doPut"))  
  502.                 ALLOW_PUT = true;  
  503.             if (m.getName().equals("doDelete"))  
  504.                 ALLOW_DELETE = true;  
  505.         }  
  506.   
  507.         String allow = null;  
  508.         if (ALLOW_GET)  
  509.             allow=METHOD_GET;  
  510.         if (ALLOW_HEAD)  
  511.             if (allow==null) allow=METHOD_HEAD;  
  512.             else allow += ", " + METHOD_HEAD;  
  513.         if (ALLOW_POST)  
  514.             if (allow==null) allow=METHOD_POST;  
  515.             else allow += ", " + METHOD_POST;  
  516.         if (ALLOW_PUT)  
  517.             if (allow==null) allow=METHOD_PUT;  
  518.             else allow += ", " + METHOD_PUT;  
  519.         if (ALLOW_DELETE)  
  520.             if (allow==null) allow=METHOD_DELETE;  
  521.             else allow += ", " + METHOD_DELETE;  
  522.         if (ALLOW_TRACE)  
  523.             if (allow==null) allow=METHOD_TRACE;  
  524.             else allow += ", " + METHOD_TRACE;  
  525.         if (ALLOW_OPTIONS)  
  526.             if (allow==null) allow=METHOD_OPTIONS;  
  527.             else allow += ", " + METHOD_OPTIONS;  
  528.   
  529.         resp.setHeader("Allow", allow);  
  530.     }  
  531.   
  532.   
  533.     /** 
  534.      * Called by the server (via the <code>service</code> method) 
  535.      * to allow a servlet to handle a TRACE request. 
  536.      * 
  537.      * A TRACE returns the headers sent with the TRACE 
  538.      * request to the client, so that they can be used in 
  539.      * debugging. There's no need to override this method. 
  540.      * 
  541.      * @param req   the {@link HttpServletRequest} object that 
  542.      *                  contains the request the client made of 
  543.      *                  the servlet 
  544.      * 
  545.      * @param resp  the {@link HttpServletResponse} object that 
  546.      *                  contains the response the servlet returns 
  547.      *                  to the client 
  548.      * 
  549.      * @exception IOException   if an input or output error occurs 
  550.      *                              while the servlet is handling the 
  551.      *                              TRACE request 
  552.      * 
  553.      * @exception ServletException  if the request for the 
  554.      *                                  TRACE cannot be handled 
  555.      */  
  556.     protected void doTrace(HttpServletRequest req, HttpServletResponse resp)  
  557.         throws ServletException, IOException  
  558.     {  
  559.   
  560.         int responseLength;  
  561.   
  562.         String CRLF = "\r\n";  
  563.         StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI())  
  564.             .append(" ").append(req.getProtocol());  
  565.   
  566.         Enumeration<String> reqHeaderEnum = req.getHeaderNames();  
  567.   
  568.         while( reqHeaderEnum.hasMoreElements() ) {  
  569.             String headerName = reqHeaderEnum.nextElement();  
  570.             buffer.append(CRLF).append(headerName).append(": ")  
  571.                 .append(req.getHeader(headerName));  
  572.         }  
  573.   
  574.         buffer.append(CRLF);  
  575.   
  576.         responseLength = buffer.length();  
  577.   
  578.         resp.setContentType("message/http");  
  579.         resp.setContentLength(responseLength);  
  580.         ServletOutputStream out = resp.getOutputStream();  
  581.         out.print(buffer.toString());  
  582.         out.close();  
  583.         return;  
  584.     }  
  585.   
  586.   
  587.     /** 
  588.      * Receives standard HTTP requests from the public 
  589.      * <code>service</code> method and dispatches 
  590.      * them to the <code>do</code><i>Method</i> methods defined in 
  591.      * this class. This method is an HTTP-specific version of the 
  592.      * {@link javax.servlet.Servlet#service} method. There's no 
  593.      * need to override this method. 
  594.      * 
  595.      * @param req   the {@link HttpServletRequest} object that 
  596.      *                  contains the request the client made of 
  597.      *                  the servlet 
  598.      * 
  599.      * @param resp  the {@link HttpServletResponse} object that 
  600.      *                  contains the response the servlet returns 
  601.      *                  to the client 
  602.      * 
  603.      * @exception IOException   if an input or output error occurs 
  604.      *                              while the servlet is handling the 
  605.      *                              HTTP request 
  606.      * 
  607.      * @exception ServletException  if the HTTP request 
  608.      *                                  cannot be handled 
  609.      * 
  610.      * @see javax.servlet.Servlet#service 
  611.      */  
  612.     protected void service(HttpServletRequest req, HttpServletResponse resp)  
  613.         throws ServletException, IOException {  
  614.   
  615.         String method = req.getMethod();  
  616.   
  617.         if (method.equals(METHOD_GET)) {  
  618.             long lastModified = getLastModified(req);  
  619.             if (lastModified == -1) {  
  620.                 // servlet doesn't support if-modified-since, no reason  
  621.                 // to go through further expensive logic  
  622.                 doGet(req, resp);  
  623.             } else {  
  624.                 long ifModifiedSince;  
  625.                 try {  
  626.                     ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);  
  627.                 } catch (IllegalArgumentException iae) {  
  628.                     // Invalid date header - proceed as if none was set  
  629.                     ifModifiedSince = -1;  
  630.                 }  
  631.                 if (ifModifiedSince < (lastModified / 1000 * 1000)) {  
  632.                     // If the servlet mod time is later, call doGet()  
  633.                     // Round down to the nearest second for a proper compare  
  634.                     // A ifModifiedSince of -1 will always be less  
  635.                     maybeSetLastModified(resp, lastModified);  
  636.                     doGet(req, resp);  
  637.                 } else {  
  638.                     resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);  
  639.                 }  
  640.             }  
  641.   
  642.         } else if (method.equals(METHOD_HEAD)) {  
  643.             long lastModified = getLastModified(req);  
  644.             maybeSetLastModified(resp, lastModified);  
  645.             doHead(req, resp);  
  646.   
  647.         } else if (method.equals(METHOD_POST)) {  
  648.             doPost(req, resp);  
  649.   
  650.         } else if (method.equals(METHOD_PUT)) {  
  651.             doPut(req, resp);  
  652.   
  653.         } else if (method.equals(METHOD_DELETE)) {  
  654.             doDelete(req, resp);  
  655.   
  656.         } else if (method.equals(METHOD_OPTIONS)) {  
  657.             doOptions(req,resp);  
  658.   
  659.         } else if (method.equals(METHOD_TRACE)) {  
  660.             doTrace(req,resp);  
  661.   
  662.         } else {  
  663.             //  
  664.             // Note that this means NO servlet supports whatever  
  665.             // method was requested, anywhere on this server.  
  666.             //  
  667.   
  668.             String errMsg = lStrings.getString("http.method_not_implemented");  
  669.             Object[] errArgs = new Object[1];  
  670.             errArgs[0] = method;  
  671.             errMsg = MessageFormat.format(errMsg, errArgs);  
  672.   
  673.             resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);  
  674.         }  
  675.     }  
  676.   
  677.   
  678.     /* 
  679.      * Sets the Last-Modified entity header field, if it has not 
  680.      * already been set and if the value is meaningful.  Called before 
  681.      * doGet, to ensure that headers are set before response data is 
  682.      * written.  A subclass might have set this header already, so we 
  683.      * check. 
  684.      */  
  685.     private void maybeSetLastModified(HttpServletResponse resp,  
  686.                                       long lastModified) {  
  687.         if (resp.containsHeader(HEADER_LASTMOD))  
  688.             return;  
  689.         if (lastModified >= 0)  
  690.             resp.setDateHeader(HEADER_LASTMOD, lastModified);  
  691.     }  
  692.   
  693.   
  694.     /** 
  695.      * Dispatches client requests to the protected 
  696.      * <code>service</code> method. There's no need to 
  697.      * override this method. 
  698.      * 
  699.      * @param req   the {@link HttpServletRequest} object that 
  700.      *                  contains the request the client made of 
  701.      *                  the servlet 
  702.      * 
  703.      * @param res   the {@link HttpServletResponse} object that 
  704.      *                  contains the response the servlet returns 
  705.      *                  to the client 
  706.      * 
  707.      * @exception IOException   if an input or output error occurs 
  708.      *                              while the servlet is handling the 
  709.      *                              HTTP request 
  710.      * 
  711.      * @exception ServletException  if the HTTP request cannot 
  712.      *                                  be handled 
  713.      * 
  714.      * @see javax.servlet.Servlet#service 
  715.      */  
  716.     @Override  
  717.     public void service(ServletRequest req, ServletResponse res)  
  718.         throws ServletException, IOException {  
  719.   
  720.         HttpServletRequest  request;  
  721.         HttpServletResponse response;  
  722.   
  723.         try {  
  724.             request = (HttpServletRequest) req;  
  725.             response = (HttpServletResponse) res;  
  726.         } catch (ClassCastException e) {  
  727.             throw new ServletException("non-HTTP request or response");  
  728.         }  
  729.         service(request, response);  
  730.     }  
  731. }  
  732.   
  733.   
  734. /* 
  735.  * A response wrapper for use in (dumb) "HEAD" support. 
  736.  * This just swallows that body, counting the bytes in order to set 
  737.  * the content length appropriately.  All other methods delegate to the 
  738.  * wrapped HTTP Servlet Response object. 
  739.  */  
  740. // file private  
  741. class NoBodyResponse extends HttpServletResponseWrapper {  
  742.     private final NoBodyOutputStream noBody;  
  743.     private PrintWriter writer;  
  744.     private boolean didSetContentLength;  
  745.   
  746.     // file private  
  747.     NoBodyResponse(HttpServletResponse r) {  
  748.         super(r);  
  749.         noBody = new NoBodyOutputStream();  
  750.     }  
  751.   
  752.     // file private  
  753.     void setContentLength() {  
  754.         if (!didSetContentLength) {  
  755.             if (writer != null) {  
  756.                 writer.flush();  
  757.             }  
  758.             super.setContentLength(noBody.getContentLength());  
  759.         }  
  760.     }  
  761.   
  762.   
  763.     // SERVLET RESPONSE interface methods  
  764.   
  765.     @Override  
  766.     public void setContentLength(int len) {  
  767.         super.setContentLength(len);  
  768.         didSetContentLength = true;  
  769.     }  
  770.   
  771.     @Override  
  772.     public void setContentLengthLong(long len) {  
  773.         super.setContentLengthLong(len);  
  774.         didSetContentLength = true;  
  775.     }  
  776.   
  777.     @Override  
  778.     public void setHeader(String name, String value) {  
  779.         super.setHeader(name, value);  
  780.         checkHeader(name);  
  781.     }  
  782.   
  783.     @Override  
  784.     public void addHeader(String name, String value) {  
  785.         super.addHeader(name, value);  
  786.         checkHeader(name);  
  787.     }  
  788.   
  789.     @Override  
  790.     public void setIntHeader(String name, int value) {  
  791.         super.setIntHeader(name, value);  
  792.         checkHeader(name);  
  793.     }  
  794.   
  795.     @Override  
  796.     public void addIntHeader(String name, int value) {  
  797.         super.addIntHeader(name, value);  
  798.         checkHeader(name);  
  799.     }  
  800.   
  801.     private void checkHeader(String name) {  
  802.         if ("content-length".equalsIgnoreCase(name)) {  
  803.             didSetContentLength = true;  
  804.         }  
  805.     }  
  806.   
  807.     @Override  
  808.     public ServletOutputStream getOutputStream() throws IOException {  
  809.         return noBody;  
  810.     }  
  811.   
  812.     @Override  
  813.     public PrintWriter getWriter() throws UnsupportedEncodingException {  
  814.   
  815.         if (writer == null) {  
  816.             OutputStreamWriter w;  
  817.   
  818.             w = new OutputStreamWriter(noBody, getCharacterEncoding());  
  819.             writer = new PrintWriter(w);  
  820.         }  
  821.         return writer;  
  822.     }  
  823. }  
  824.   
  825.   
  826. /* 
  827.  * Servlet output stream that gobbles up all its data. 
  828.  */  
  829.   
  830. // file private  
  831. class NoBodyOutputStream extends ServletOutputStream {  
  832.   
  833.     private static final String LSTRING_FILE =  
  834.         "javax.servlet.http.LocalStrings";  
  835.     private static final ResourceBundle lStrings =  
  836.         ResourceBundle.getBundle(LSTRING_FILE);  
  837.   
  838.     private int contentLength = 0;  
  839.   
  840.     // file private  
  841.     NoBodyOutputStream() {  
  842.         // NOOP  
  843.     }  
  844.   
  845.     // file private  
  846.     int getContentLength() {  
  847.         return contentLength;  
  848.     }  
  849.   
  850.     @Override  
  851.     public void write(int b) {  
  852.         contentLength++;  
  853.     }  
  854.   
  855.     @Override  
  856.     public void write(byte buf[], int offset, int len) throws IOException {  
  857.         if (buf == null) {  
  858.             throw new NullPointerException(  
  859.                     lStrings.getString("err.io.nullArray"));  
  860.         }  
  861.   
  862.         if (offset < 0 || len < 0 || offset+len > buf.length) {  
  863.             String msg = lStrings.getString("err.io.indexOutOfBounds");  
  864.             Object[] msgArgs = new Object[3];  
  865.             msgArgs[0] = Integer.valueOf(offset);  
  866.             msgArgs[1] = Integer.valueOf(len);  
  867.             msgArgs[2] = Integer.valueOf(buf.length);  
  868.             msg = MessageFormat.format(msg, msgArgs);  
  869.             throw new IndexOutOfBoundsException(msg);  
  870.         }  
  871.   
  872.         contentLength += len;  
  873.     }  
  874.   
  875.     @Override  
  876.     public boolean isReady() {  
  877.         // TODO SERVLET 3.1  
  878.         return false;  
  879.     }  
  880.   
  881.     @Override  
  882.     public void setWriteListener(javax.servlet.WriteListener listener) {  
  883.         // TODO SERVLET 3.1  
  884.     }  
  885. }  

 

 

GenericServlet源码:

 

[java]  view plain  copy
 
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  * 
  9.  *     http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17. package javax.servlet;  
  18.   
  19. import java.io.IOException;  
  20. import java.util.Enumeration;  
  21.   
  22. /** 
  23.  * Defines a generic, protocol-independent servlet. To write an HTTP servlet for 
  24.  * use on the Web, extend {@link javax.servlet.http.HttpServlet} instead. 
  25.  * <p> 
  26.  * <code>GenericServlet</code> implements the <code>Servlet</code> and 
  27.  * <code>ServletConfig</code> interfaces. <code>GenericServlet</code> may be 
  28.  * directly extended by a servlet, although it's more common to extend a 
  29.  * protocol-specific subclass such as <code>HttpServlet</code>. 
  30.  * <p> 
  31.  * <code>GenericServlet</code> makes writing servlets easier. It provides simple 
  32.  * versions of the lifecycle methods <code>init</code> and <code>destroy</code> 
  33.  * and of the methods in the <code>ServletConfig</code> interface. 
  34.  * <code>GenericServlet</code> also implements the <code>log</code> method, 
  35.  * declared in the <code>ServletContext</code> interface. 
  36.  * <p> 
  37.  * To write a generic servlet, you need only override the abstract 
  38.  * <code>service</code> method. 
  39.  */  
  40. public abstract class GenericServlet implements Servlet, ServletConfig,  
  41.         java.io.Serializable {  
  42.   
  43.     private static final long serialVersionUID = 1L;  
  44.   
  45.     private transient ServletConfig config;  
  46.   
  47.     /** 
  48.      * Does nothing. All of the servlet initialization is done by one of the 
  49.      * <code>init</code> methods. 
  50.      */  
  51.     public GenericServlet() {  
  52.         // NOOP  
  53.     }  
  54.   
  55.     /** 
  56.      * Called by the servlet container to indicate to a servlet that the servlet 
  57.      * is being taken out of service. See {@link Servlet#destroy}. 
  58.      */  
  59.     @Override  
  60.     public void destroy() {  
  61.         // NOOP by default  
  62.     }  
  63.   
  64.     /** 
  65.      * Returns a <code>String</code> containing the value of the named 
  66.      * initialization parameter, or <code>null</code> if the parameter does not 
  67.      * exist. See {@link ServletConfig#getInitParameter}. 
  68.      * <p> 
  69.      * This method is supplied for convenience. It gets the value of the named 
  70.      * parameter from the servlet's <code>ServletConfig</code> object. 
  71.      * 
  72.      * @param name 
  73.      *            a <code>String</code> specifying the name of the 
  74.      *            initialization parameter 
  75.      * @return String a <code>String</code> containing the value of the 
  76.      *         initialization parameter 
  77.      */  
  78.     @Override  
  79.     public String getInitParameter(String name) {  
  80.         return getServletConfig().getInitParameter(name);  
  81.     }  
  82.   
  83.     /** 
  84.      * Returns the names of the servlet's initialization parameters as an 
  85.      * <code>Enumeration</code> of <code>String</code> objects, or an empty 
  86.      * <code>Enumeration</code> if the servlet has no initialization parameters. 
  87.      * See {@link ServletConfig#getInitParameterNames}. 
  88.      * <p> 
  89.      * This method is supplied for convenience. It gets the parameter names from 
  90.      * the servlet's <code>ServletConfig</code> object. 
  91.      * 
  92.      * @return Enumeration an enumeration of <code>String</code> objects 
  93.      *         containing the names of the servlet's initialization parameters 
  94.      */  
  95.     @Override  
  96.     public Enumeration<String> getInitParameterNames() {  
  97.         return getServletConfig().getInitParameterNames();  
  98.     }  
  99.   
  100.     /** 
  101.      * Returns this servlet's {@link ServletConfig} object. 
  102.      * 
  103.      * @return ServletConfig the <code>ServletConfig</code> object that 
  104.      *         initialized this servlet 
  105.      */  
  106.     @Override  
  107.     public ServletConfig getServletConfig() {  
  108.         return config;  
  109.     }  
  110.   
  111.     /** 
  112.      * Returns a reference to the {@link ServletContext} in which this servlet 
  113.      * is running. See {@link ServletConfig#getServletContext}. 
  114.      * <p> 
  115.      * This method is supplied for convenience. It gets the context from the 
  116.      * servlet's <code>ServletConfig</code> object. 
  117.      * 
  118.      * @return ServletContext the <code>ServletContext</code> object passed to 
  119.      *         this servlet by the <code>init</code> method 
  120.      */  
  121.     @Override  
  122.     public ServletContext getServletContext() {  
  123.         return getServletConfig().getServletContext();  
  124.     }  
  125.   
  126.     /** 
  127.      * Returns information about the servlet, such as author, version, and 
  128.      * copyright. By default, this method returns an empty string. Override this 
  129.      * method to have it return a meaningful value. See 
  130.      * {@link Servlet#getServletInfo}. 
  131.      * 
  132.      * @return String information about this servlet, by default an empty string 
  133.      */  
  134.     @Override  
  135.     public String getServletInfo() {  
  136.         return "";  
  137.     }  
  138.   
  139.     /** 
  140.      * Called by the servlet container to indicate to a servlet that the servlet 
  141.      * is being placed into service. See {@link Servlet#init}. 
  142.      * <p> 
  143.      * This implementation stores the {@link ServletConfig} object it receives 
  144.      * from the servlet container for later use. When overriding this form of 
  145.      * the method, call <code>super.init(config)</code>. 
  146.      * 
  147.      * @param config 
  148.      *            the <code>ServletConfig</code> object that contains 
  149.      *            configuration information for this servlet 
  150.      * @exception ServletException 
  151.      *                if an exception occurs that interrupts the servlet's 
  152.      *                normal operation 
  153.      * @see UnavailableException 
  154.      */  
  155.     @Override  
  156.     public void init(ServletConfig config) throws ServletException {  
  157.         this.config = config;  
  158.         this.init();  
  159.     }  
  160.   
  161.     /** 
  162.      * A convenience method which can be overridden so that there's no need to 
  163.      * call <code>super.init(config)</code>. 
  164.      * <p> 
  165.      * Instead of overriding {@link #init(ServletConfig)}, simply override this 
  166.      * method and it will be called by 
  167.      * <code>GenericServlet.init(ServletConfig config)</code>. The 
  168.      * <code>ServletConfig</code> object can still be retrieved via 
  169.      * {@link #getServletConfig}. 
  170.      * 
  171.      * @exception ServletException 
  172.      *                if an exception occurs that interrupts the servlet's 
  173.      *                normal operation 
  174.      */  
  175.     public void init() throws ServletException {  
  176.         // NOOP by default  
  177.     }  
  178.   
  179.     /** 
  180.      * Writes the specified message to a servlet log file, prepended by the 
  181.      * servlet's name. See {@link ServletContext#log(String)}. 
  182.      * 
  183.      * @param msg 
  184.      *            a <code>String</code> specifying the message to be written to 
  185.      *            the log file 
  186.      */  
  187.     public void log(String msg) {  
  188.         getServletContext().log(getServletName() + ": " + msg);  
  189.     }  
  190.   
  191.     /** 
  192.      * Writes an explanatory message and a stack trace for a given 
  193.      * <code>Throwable</code> exception to the servlet log file, prepended by 
  194.      * the servlet's name. See {@link ServletContext#log(String, Throwable)}. 
  195.      * 
  196.      * @param message 
  197.      *            a <code>String</code> that describes the error or exception 
  198.      * @param t 
  199.      *            the <code>java.lang.Throwable</code> error or exception 
  200.      */  
  201.     public void log(String message, Throwable t) {  
  202.         getServletContext().log(getServletName() + ": " + message, t);  
  203.     }  
  204.   
  205.     /** 
  206.      * Called by the servlet container to allow the servlet to respond to a 
  207.      * request. See {@link Servlet#service}. 
  208.      * <p> 
  209.      * This method is declared abstract so subclasses, such as 
  210.      * <code>HttpServlet</code>, must override it. 
  211.      * 
  212.      * @param req 
  213.      *            the <code>ServletRequest</code> object that contains the 
  214.      *            client's request 
  215.      * @param res 
  216.      *            the <code>ServletResponse</code> object that will contain the 
  217.      *            servlet's response 
  218.      * @exception ServletException 
  219.      *                if an exception occurs that interferes with the servlet's 
  220.      *                normal operation occurred 
  221.      * @exception IOException 
  222.      *                if an input or output exception occurs 
  223.      */  
  224.     @Override  
  225.     public abstract void service(ServletRequest req, ServletResponse res)  
  226.             throws ServletException, IOException;  
  227.   
  228.     /** 
  229.      * Returns the name of this servlet instance. See 
  230.      * {@link ServletConfig#getServletName}. 
  231.      * 
  232.      * @return the name of this servlet instance 
  233.      */  
  234.     @Override  
  235.     public String getServletName() {  
  236.         return config.getServletName();  
  237.     }  
  238. }  

 

 

 

Servlet源码:

 

[java]  view plain  copy
 
  1. /* 
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more 
  3.  * contributor license agreements.  See the NOTICE file distributed with 
  4.  * this work for additional information regarding copyright ownership. 
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0 
  6.  * (the "License"); you may not use this file except in compliance with 
  7.  * the License.  You may obtain a copy of the License at 
  8.  * 
  9.  *     http://www.apache.org/licenses/LICENSE-2.0 
  10.  * 
  11.  * Unless required by applicable law or agreed to in writing, software 
  12.  * distributed under the License is distributed on an "AS IS" BASIS, 
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  14.  * See the License for the specific language governing permissions and 
  15.  * limitations under the License. 
  16.  */  
  17.   
  18. package javax.servlet;  
  19.   
  20. import java.io.IOException;  
  21.   
  22. /** 
  23.  * Defines methods that all servlets must implement. 
  24.  * 
  25.  * <p> 
  26.  * A servlet is a small Java program that runs within a Web server. Servlets 
  27.  * receive and respond to requests from Web clients, usually across HTTP, the 
  28.  * HyperText Transfer Protocol. 
  29.  * 
  30.  * <p> 
  31.  * To implement this interface, you can write a generic servlet that extends 
  32.  * <code>javax.servlet.GenericServlet</code> or an HTTP servlet that extends 
  33.  * <code>javax.servlet.http.HttpServlet</code>. 
  34.  * 
  35.  * <p> 
  36.  * This interface defines methods to initialize a servlet, to service requests, 
  37.  * and to remove a servlet from the server. These are known as life-cycle 
  38.  * methods and are called in the following sequence: 
  39.  * <ol> 
  40.  * <li>The servlet is constructed, then initialized with the <code>init</code> 
  41.  * method. 
  42.  * <li>Any calls from clients to the <code>service</code> method are handled. 
  43.  * <li>The servlet is taken out of service, then destroyed with the 
  44.  * <code>destroy</code> method, then garbage collected and finalized. 
  45.  * </ol> 
  46.  * 
  47.  * <p> 
  48.  * In addition to the life-cycle methods, this interface provides the 
  49.  * <code>getServletConfig</code> method, which the servlet can use to get any 
  50.  * startup information, and the <code>getServletInfo</code> method, which allows 
  51.  * the servlet to return basic information about itself, such as author, 
  52.  * version, and copyright. 
  53.  * 
  54.  * @see GenericServlet 
  55.  * @see javax.servlet.http.HttpServlet 
  56.  */  
  57. public interface Servlet {  
  58.   
  59.     /** 
  60.      * Called by the servlet container to indicate to a servlet that the servlet 
  61.      * is being placed into service. 
  62.      * 
  63.      * <p> 
  64.      * The servlet container calls the <code>init</code> method exactly once 
  65.      * after instantiating the servlet. The <code>init</code> method must 
  66.      * complete successfully before the servlet can receive any requests. 
  67.      * 
  68.      * <p> 
  69.      * The servlet container cannot place the servlet into service if the 
  70.      * <code>init</code> method 
  71.      * <ol> 
  72.      * <li>Throws a <code>ServletException</code> 
  73.      * <li>Does not return within a time period defined by the Web server 
  74.      * </ol> 
  75.      * 
  76.      * 
  77.      * @param config 
  78.      *            a <code>ServletConfig</code> object containing the servlet's 
  79.      *            configuration and initialization parameters 
  80.      * 
  81.      * @exception ServletException 
  82.      *                if an exception has occurred that interferes with the 
  83.      *                servlet's normal operation 
  84.      * 
  85.      * @see UnavailableException 
  86.      * @see #getServletConfig 
  87.      */  
  88.     public void init(ServletConfig config) throws ServletException;  
  89.   
  90.     /** 
  91.      * 
  92.      * Returns a {@link ServletConfig} object, which contains initialization and 
  93.      * startup parameters for this servlet. The <code>ServletConfig</code> 
  94.      * object returned is the one passed to the <code>init</code> method. 
  95.      * 
  96.      * <p> 
  97.      * Implementations of this interface are responsible for storing the 
  98.      * <code>ServletConfig</code> object so that this method can return it. The 
  99.      * {@link GenericServlet} class, which implements this interface, already 
  100.      * does this. 
  101.      * 
  102.      * @return the <code>ServletConfig</code> object that initializes this 
  103.      *         servlet 
  104.      * 
  105.      * @see #init 
  106.      */  
  107.     public ServletConfig getServletConfig();  
  108.   
  109.     /** 
  110.      * Called by the servlet container to allow the servlet to respond to a 
  111.      * request. 
  112.      * 
  113.      * <p> 
  114.      * This method is only called after the servlet's <code>init()</code> method 
  115.      * has completed successfully. 
  116.      * 
  117.      * <p> 
  118.      * The status code of the response always should be set for a servlet that 
  119.      * throws or sends an error. 
  120.      * 
  121.      * 
  122.      * <p> 
  123.      * Servlets typically run inside multithreaded servlet containers that can 
  124.      * handle multiple requests concurrently. Developers must be aware to 
  125.      * synchronize access to any shared resources such as files, network 
  126.      * connections, and as well as the servlet's class and instance variables. 
  127.      * More information on multithreaded programming in Java is available in <a 
  128.      * href 
  129.      * ="http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html"> 
  130.      * the Java tutorial on multi-threaded programming</a>. 
  131.      * 
  132.      * 
  133.      * @param req 
  134.      *            the <code>ServletRequest</code> object that contains the 
  135.      *            client's request 
  136.      * 
  137.      * @param res 
  138.      *            the <code>ServletResponse</code> object that contains the 
  139.      *            servlet's response 
  140.      * 
  141.      * @exception ServletException 
  142.      *                if an exception occurs that interferes with the servlet's 
  143.      *                normal operation 
  144.      * 
  145.      * @exception IOException 
  146.      *                if an input or output exception occurs 
  147.      */  
  148.     public void service(ServletRequest req, ServletResponse res)  
  149.             throws ServletException, IOException;  
  150.   
  151.     /** 
  152.      * Returns information about the servlet, such as author, version, and 
  153.      * copyright. 
  154.      * 
  155.      * <p> 
  156.      * The string that this method returns should be plain text and not markup 
  157.      * of any kind (such as HTML, XML, etc.). 
  158.      * 
  159.      * @return a <code>String</code> containing servlet information 
  160.      */  
  161.     public String getServletInfo();  
  162.   
  163.     /** 
  164.      * Called by the servlet container to indicate to a servlet that the servlet 
  165.      * is being taken out of service. This method is only called once all 
  166.      * threads within the servlet's <code>service</code> method have exited or 
  167.      * after a timeout period has passed. After the servlet container calls this 
  168.      * method, it will not call the <code>service</code> method again on this 
  169.      * servlet. 
  170.      * 
  171.      * <p> 
  172.      * This method gives the servlet an opportunity to clean up any resources 
  173.      * that are being held (for example, memory, file handles, threads) and make 
  174.      * sure that any persistent state is synchronized with the servlet's current 
  175.      * state in memory. 
  176.      */  
  177.     public void destroy();  
  178. }  
目录
相关文章
|
8月前
|
应用服务中间件
Servlet - 匹配模式加注解源码分析
Servlet - 匹配模式加注解源码分析
54 0
|
11月前
|
应用服务中间件
Tomcat - 源码分析Tomcat是如何处理一个Servlet请求的
Tomcat - 源码分析Tomcat是如何处理一个Servlet请求的
55 0
|
XML 应用服务中间件 Linux
从源码分析tomcat如何调用Servlet的初始化
从源码分析tomcat如何调用Servlet的初始化
233 0
从源码分析tomcat如何调用Servlet的初始化
|
应用服务中间件 容器
Servlet容器Tomcat中web.xml中url-pattern的配置详解[附带源码分析]
http://www.cnblogs.com/fangjian0423/p/servletContainer-tomcat-urlPattern.html#springmvc
1124 0
|
24天前
|
Java
学校教师管理系统【JSP+Servlet+JavaBean】(Java课设)
学校教师管理系统【JSP+Servlet+JavaBean】(Java课设)
19 1
|
24天前
|
Java
人事管理系统【JSP+Servlet+JavaBean】(Java课设)
人事管理系统【JSP+Servlet+JavaBean】(Java课设)
19 0
|
1月前
使用Servlet上传多张图片——前台页面层(Index.jsp)
使用Servlet上传多张图片——前台页面层(Index.jsp)
14 0
|
24天前
|
Java
排课系统【JSP+Servlet+JavaBean】(Java课设)
排课系统【JSP+Servlet+JavaBean】(Java课设)
7 0
|
24天前
|
Java
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
仓库管理系统【JSP+Servlet+JavaBean】(Java课设)
13 0