servlet构造response,以及获取RequestDispatcher对象

来源:互联网 发布:淘宝网夏季新款女装 编辑:程序博客网 时间:2024/05/26 19:19

Constructing Responses
A response contains data passed between a server and the client. All responses implement the
ServletResponse interface. This interface defines methods that allow you to
■ Retrieve an output stream to use to send data to the client. To send character data, use the
PrintWriter returned by the response’s getWriter method. To send binary data in a
Multipurpose InternetMail Extensions (MIME) body response, use the
ServletOutputStream returned by getOutputStream. To mix binary and text data, as in a
multipart response, use a ServletOutputStream and manage the character sections
manually.
■ Indicate the content type (for example, text/html) being returned by the response with the
setContentType(String) method. This method must be called before the response is
committed. A registry of content type names is kept by the Internet AssignedNumbers
Authority (IANA) at http://www.iana.org/assignments/media-types/.
■ Indicate whether to buffer output with the setBufferSize(int) method. By default, any
content written to the output stream is immediately sent to the client. Buffering allows
content to be written before anything is sent back to the client, thus providing the servlet
Writing ServiceMethods
Chapter 10 • Java Servlet Technology 203
with more time to set appropriate status codes and headers or forward to another web
resource. The method must be called before any content is written or before the response is
committed.
■ Set localization information, such as locale and character encoding.

 

To invoke a resource available on the server that is running a web component, you must first
obtain a RequestDispatcher object by using the getRequestDispatcher("URL") method. You
can get a RequestDispatcher object from either a request or the web context; however, the two
methods have slightly different behavior. The method takes the path to the requested resource
as an argument. A request can take a relative path (that is, one that does not begin with a /), but
the web context requires an absolute path. If the resource is not available or if the server has not
implemented a RequestDispatcher object for that type of resource, getRequestDispatcher
will return null. Your servlet should be prepared to deal with this condition.

原创粉丝点击