HttpServlet (Java EE 5)

Java EE API


javax.servlet.http Class HttpServlet

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
All Implemented Interfaces:
Serializable, Servlet, ServletConfig

public abstract class HttpServlet
extends GenericServlet
implements Serializable

Implements: java.io.Serializable

提供将要被子类化以创建适用于 Web 站点的 HTTP servlet 的抽象类。HttpServlet 的子类至少必须重写一个方法,该方法通常是以下这些方法之一:
  • doGet,如果 servlet 支持 HTTP GET 请求
  • doPost,用于 HTTP POST 请求
  • doPut,用于 HTTP PUT 请求
  • doDelete,用于 HTTP DELETE 请求
  • initdestroy,用于管理 servlet 的生命周期内保存的资源
  • getServletInfo,servlet 使用它提供有关其自身的信息

几乎没有理由重写 service 方法。service 通过将标准 HTTP 请求分发给每个 HTTP 请求类型的处理程序方法(上面列出的 doXXX 方法)来处理它们。

同样,几乎没有理由重写 doOptionsdoTrace 方法。

servlet 通常运行在多线程服务器上,因此应该意识到 servlet 必须处理并发请求并小心地同步对共享资源的访问。共享资源包括内存数据(比如实例或类变量)和外部对象(比如文件、数据库连接和网络连接)。有关在 Java 程序中处理多个线程的更多信息,请参见 Java Tutorial on Multithreaded Programming

英文文档:

Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

Likewise, there's almost no reason to override the doOptions and doTrace methods.

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 Java Tutorial on Multithreaded Programming for more information on handling multiple threads in a Java program.

Author:
Various
See Also:
Serialized Form

Constructor Summary
 
Method Summary
protected  void
protected  void
protected  void
protected  void
protected  void
protected  void
protected  void
protected  long
protected  void
 void
 
Methods inherited from class javax.servlet.GenericServlet
 
Methods inherited from class java.lang.Object
 

Constructor Detail

public HttpServlet()
不执行任何操作,因为这是一个抽象类。
英文文档:

HttpServlet

public HttpServlet()
Does nothing, because this is an abstract class.

Method Detail

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 GET 请求。

重写此方法以支持 GET 请求,也就自动支持了 HTTP HEAD 请求。HEAD 请求是一个返回响应中没有正文、只有请求头字段的 GET 请求。

重写此方法时,读取请求数据、写入响应头、获取响应的编写者或输出流对象,最后,写入响应数据。最好包括内容类型和编码。使用 PrintWriter 对象返回响应时,在访问 PrintWriter 对象之前设置内容类型。

提交响应前,servlet 容器必须写入响应头,因为在 HTTP 中响应头必须在响应正文之前发送。

如有可能,应设置 Content-Length 头(使用 javax.servlet.ServletResponse#setContentLength 方法),以允许 servlet 容器使用持久连接向客户端返回响应,从而改进性能。如果响应缓冲区能够容纳整个响应,则自动设置内容长度。

使用 HTTP 1.1 存储块编码时(这意味着响应具有 Transfer-Encoding 头),不要设置 Content-Length 头。

GET 方法应该是安全的,也就是说,没有需要用户负责的任何副作用。例如,大多数形式查询没有副作用。如果某个客户端请求用于更改存储数据,则该请求应该使用某个其他 HTTP 方法。

GET 方法还应该是幂等的,这意味着可以安全地重复使用它。有时使某个方法是安全的也会使其成为幂等的。例如,重复查询既是安全的,又是幂等的,但在线购买某个产品或修改数据则既不是安全的又不是幂等的。

如果不正确地格式化请求,则 doGet 将返回一条 HTTP "Bad Request" 消息。

req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端发送的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理 GET 请求期间检测到输入或输出错误
ThrowsServletException: 如果无法处理对 GET 的请求
See also setContentType

英文文档:

doGet

protected void doGet(HttpServletRequest req,
                     HttpServletResponse resp)
              throws ServletException,
                     IOException
Called by the server (via the service method) to allow a servlet to handle a GET request.

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.

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 PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.

Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) 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.

When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.

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.

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.

If the request is incorrectly formatted, doGet returns an HTTP "Bad Request" message.

Parameters:
req - an HttpServletRequest object that contains the request the client has made of the servlet
resp - an HttpServletResponse object that contains the response the servlet sends to the client
Throws:
IOException - if an input or output error is detected when the servlet handles the GET request
ServletException - if the request for the GET could not be handled
See Also:
ServletResponse.setContentType(java.lang.String)

protected long getLastModified(HttpServletRequest req)
返回上次修改 HttpServletRequest 对象的时间,该时间是自格林威治标准时间 1970 年 1 月 1 日午夜起经过的毫秒数。如果该时间是未知的,则此方法返回一个负数(默认值)。

支持 HTTP GET 请求并且可以快速确定其上次修改时间的 servlet 应该重写此方法。这使浏览器和代理缓存更有效地工作,减少服务器和网络资源上的负载。

req 发送给 servlet 的 HttpServletRequest 对象
return 指定 HttpServletRequest 对象的上次修改时间的 long 整数,该时间是自格林威治标准时间 1970 年 1 月 1 日午夜起经过的毫秒数,如果该时间是未知的,则返回 -1

英文文档:

getLastModified

protected long getLastModified(HttpServletRequest req)
Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT. If the time is unknown, this method returns a negative number (the default).

Servlets that support HTTP GET requests and can quickly determine their last modification time should override this method. This makes browser and proxy caches work more effectively, reducing the load on server and network resources.

Parameters:
req - the HttpServletRequest object that is sent to the servlet
Returns:
a long integer specifying the time the HttpServletRequest object was last modified, in milliseconds since midnight, January 1, 1970 GMT, or -1 if the time is not known

protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException

接收来自受保护 service 方法的 HTTP HEAD 请求并处理该请求。当客户端只想看到响应的头(比如 Content-Type 或 Content-Length)时,它可以发送一个 HEAD 请求。HTTP HEAD 方法计算响应中的输出字节数,以便准确设置 Content-Length 头。

如果重写此方法,可以避免计算响应正文而仅直接设置响应头,从而提高性能。确保编写的 doHead 方法是既安全又幂等的(也就是说,保护它自己不被一个 HTTP HEAD 请求多次调用)。

如果不正确地格式化 HTTP HEAD 请求,则 doHead 将返回一条 HTTP "Bad Request" 消息。

req 传递给 servlet 的请求对象
resp servlet 用来将头返回给客户端的响应对象
Throwsjava.io.IOException: 如果发生输入或输出错误
ThrowsServletException: 如果无法处理对 HEAD 的请求

英文文档:

doHead

protected void doHead(HttpServletRequest req,
                      HttpServletResponse resp)
               throws ServletException,
                      IOException

Receives an HTTP HEAD request from the protected service method and handles the request. The client sends a HEAD request when it wants to see only the headers of a response, such as Content-Type or Content-Length. The HTTP HEAD method counts the output bytes in the response to set the Content-Length header accurately.

If you override this method, you can avoid computing the response body and just set the response headers directly to improve performance. Make sure that the doHead method you write is both safe and idempotent (that is, protects itself from being called multiple times for one HTTP HEAD request).

If the HTTP HEAD request is incorrectly formatted, doHead returns an HTTP "Bad Request" message.

Parameters:
req - the request object that is passed to the servlet
resp - the response object that the servlet uses to return the headers to the clien
Throws:
IOException - if an input or output error occurs
ServletException - if the request for the HEAD could not be handled

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 POST 请求。 HTTP POST 方法允许客户端一次将不限长度的数据发送到 Web 服务器,这在发送诸如信用卡号之类的信息时很有用。

重写此方法时,读取请求数据、写入响应头、获取响应的编写者或输出流对象,最后,写入响应数据。最好包括内容类型和编码。使用 PrintWriter 对象返回响应时,在访问 PrintWriter 对象之前设置内容类型。

提交响应前,servlet 容器必须写入响应头,因为在 HTTP 中响应头必须在响应正文之前发送。

如有可能,应设置 Content-Length 头(使用 javax.servlet.ServletResponse#setContentLength 方法),以允许 servlet 容器使用持久连接向客户端返回响应,从而改进性能。如果响应缓冲区能够容纳整个响应,则自动设置内容长度。

使用 HTTP 1.1 存储块编码时(这意味着响应具有 Transfer-Encoding 头),不要设置 Content-Length 头。

此方法不需要是安全的或幂等的。通过 POST 请求的操作可能产生用户需要负责的副作用,例如,更新存储数据或在线购买商品。

如果不正确地格式化 HTTP POST 请求,则 doPost 返回一条 HTTP "Bad Request" 消息。

req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端发送的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理该请求期间检测到输入或输出错误
ThrowsServletException: 如果无法处理对 POST 的请求
See also javax.servlet.ServletOutputStream, setContentType

英文文档:

doPost

protected void doPost(HttpServletRequest req,
                      HttpServletResponse resp)
               throws ServletException,
                      IOException
Called by the server (via the service 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.

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 PrintWriter object to return the response, set the content type before accessing the PrintWriter object.

The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.

Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int) 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.

When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding header), do not set the Content-Length header.

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.

If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad Request" message.

Parameters:
req - an HttpServletRequest object that contains the request the client has made of the servlet
resp - an HttpServletResponse object that contains the response the servlet sends to the client
Throws:
IOException - if an input or output error is detected when the servlet handles the request
ServletException - if the request for the POST could not be handled
See Also:
ServletOutputStream, ServletResponse.setContentType(java.lang.String)

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 PUT 请求。 PUT 操作允许客户端将文件放在服务器上,类似于通过 FTP 发送文件。

在重写此方法时,随请求一起发送的所有内容头都要保持原样,这些内容头包括 Content-Length、Content-Type、Content-Transfer-Encoding、Content-Encoding、Content-Base、Content-Language、Content-Location、Content-MD5 和 Content-Range。如果某个方法无法处理内容头,则它必须发出一条错误消息 (HTTP 501 - Not Implemented) 并丢弃该请求。有关 HTTP 1.1 的更多信息,请参见 RFC 2616 。

此方法不需要是安全的或幂等的。doPut 执行的操作可能具有用户需要负责的副作用。使用此方法时,在临时存储器中保存受影响 URL 的副本可能会很有用。

如果不正确地格式化 HTTP PUT 请求,则 doPut 返回一条 HTTP "Bad Request" 消息。

req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理 PUT 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理对 PUT 的请求

英文文档:

doPut

protected void doPut(HttpServletRequest req,
                     HttpServletResponse resp)
              throws ServletException,
                     IOException
Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.

When overriding this method, leave intact any content headers sent with the request (including Content-Length, Content-Type, Content-Transfer-Encoding, Content-Encoding, Content-Base, Content-Language, Content-Location, Content-MD5, and Content-Range). If your method cannot handle a content header, it must issue an error message (HTTP 501 - Not Implemented) and discard the request. For more information on HTTP 1.1, see RFC 2616 .

This method does not need to be either safe or idempotent. Operations that doPut performs can have side effects for which the user can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

If the HTTP PUT request is incorrectly formatted, doPut returns an HTTP "Bad Request" message.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the PUT request
ServletException - if the request for the PUT cannot be handled

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 DELETE 请求。 DELETE 操作允许客户端从服务器中移除文档或 Web 页面。

此方法不需要是安全的或幂等的。通过 DELETE 请求的操作可能具有用户需要负责的副作用。使用此方法时,在临时存储器中保存受影响 URL 的副本可能会很有用。

如果不正确地格式化 HTTP DELETE 请求,则 doDelete 返回一条 HTTP "Bad Request" 消息。

req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理 DELETE 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理对 DELETE 的请求

英文文档:

doDelete

protected void doDelete(HttpServletRequest req,
                        HttpServletResponse resp)
                 throws ServletException,
                        IOException
Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or Web page from the server.

This method does not need to be either safe or idempotent. Operations requested through DELETE can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

If the HTTP DELETE request is incorrectly formatted, doDelete returns an HTTP "Bad Request" message.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the DELETE request
ServletException - if the request for the DELETE cannot be handled

protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 OPTIONS 请求。 OPTIONS 请求可确定服务器支持哪些 HTTP 方法,并返回相应的头。例如,如果 servlet 重写 doGet,则此方法返回以下头:

Allow:GET, HEAD, TRACE, OPTIONS

无需重写此方法,除非 servlet 实现了 HTTP 1.1 实现的那些方法以外的新 HTTP 方法。

req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理 OPTIONS 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理对 OPTIONS 的请求

英文文档:

doOptions

protected void doOptions(HttpServletRequest req,
                         HttpServletResponse resp)
                  throws ServletException,
                         IOException
Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For example, if a servlet overrides doGet, this method returns the following header:

Allow: GET, HEAD, TRACE, OPTIONS

There's no need to override this method unless the servlet implements new HTTP methods, beyond those implemented by HTTP 1.1.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the OPTIONS request
ServletException - if the request for the OPTIONS cannot be handled

protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
由服务器调用(通过 service 方法),以允许 servlet 处理 TRACE 请求。 TRACE 将随 TRACE 请求一起发送的头返回给客户端,以便在调试中使用它们。无需重写此方法。
req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在 servlet 处理 TRACE 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理对 TRACE 的请求
英文文档:

doTrace

protected void doTrace(HttpServletRequest req,
                       HttpServletResponse resp)
                throws ServletException,
                       IOException
Called by the server (via the service method) to allow a servlet to handle a TRACE request. A TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There's no need to override this method.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the TRACE request
ServletException - if the request for the TRACE cannot be handled

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
接收来自 public service 方法的标准 HTTP 请求,并将它们分发给此类中定义的 doXXX 方法。此方法是 javax.servlet.Servlet#service 方法的特定于 HTTP 的版本。无需重写此方法。
req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
resp 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在处理 HTTP 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理 HTTP 请求
See also service
英文文档:

service

protected void service(HttpServletRequest req,
                       HttpServletResponse resp)
                throws ServletException,
                       IOException
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There's no need to override this method.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the HTTP request
ServletException - if the HTTP request cannot be handled
See Also:
Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)

public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
将客户端请求分发给受保护的 service 方法。无需重写此方法。
req 包含客户端对 servlet 发出的请求的 HttpServletRequest 对象
res 包含 servlet 向客户端返回的响应的 HttpServletResponse 对象
Throwsjava.io.IOException: 如果在处理 HTTP 请求期间发生输入或输出错误
ThrowsServletException: 如果无法处理 HTTP 请求
See also service
英文文档:

service

public void service(ServletRequest req,
                    ServletResponse res)
             throws ServletException,
                    IOException
Dispatches client requests to the protected service method. There's no need to override this method.

Specified by:
service in interface Servlet
Specified by:
service in class GenericServlet
Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
res - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
IOException - if an input or output error occurs while the servlet is handling the HTTP request
ServletException - if the HTTP request cannot be handled
See Also:
Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)


Submit a bug or feature

Copyright 2007 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.

一看就知道只有菜鸟才干这么无知的事啦。

PS : 未经我党受权你也可自由散发此文档。 如有任何错误请自行修正;若因此而造成任何损失请直接找人民主席,请勿与本人联系。谢谢!