Javaweb---Summary (vii) HttpServletResponse object (i)

Source: Internet
Author: User

The Web server receives an HTTP request from the client, creating a Request object for each request, and a response object representing the response, respectively.

The request and response objects represent requests and responses, so we need to get the data submitted by the client, just find the request object. To output data to a client, you just need to find the response object.

First, HttpServletResponse object introduction

  

The HttpServletResponse object represents the response of the server. This object encapsulates the method of sending data to the client, sending a response header, and sending a response status code. Look at the HttpServletResponse API to see these related methods.

1.1, responsible for sending data to the client (browser) related methods

  

1.2, responsible for sending the response header to the client (browser) related methods

  

  

1.3, responsible for sending the response status code to the client (browser) related methods

  

1.4, the constant response status code

HttpServletResponse defines a number of constants for the status code (see the Servlet's API), which can be used when a response status code needs to be sent to the client, avoiding direct write numbers, and constants that correspond to common status codes:

Constants corresponding to status code 404

  

Constants corresponding to status code 200

  

Constants corresponding to status code 500

  

Ii. Common Application of HttpServletResponse objects 2.1, use OutputStream flow to the client browser output Chinese data

Use OutputStream stream to output Chinese note the problem:

On the server side, the data is the Code table output, then control the client browser with the corresponding code table open, such as: Outputstream.write ("China". GetBytes ("UTF-8")); Use OutputStream flow to the client browser output Chinese, to UTF-8 encoding for output, at this time to control the client browser to UTF-8 encoding open, otherwise display will appear in Chinese garbled, So how does the server side control the client browser to display the data in UTF-8 encoding? You can control the behavior of the browser by setting the response header, for example: Response.setheader ("Content-type", "Text/html;charset=utf-8"), and by setting the response header to control the browser to display the data in UTF-8 encoding.

Example: Using the OutputStream to flow to the client browser output "China" two characters

 1 package gacl.response.study; 2 3 Import java.io.IOException; 4 Import Java.io.OutputStream; 5 Import javax.servlet.ServletException; 6 Import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse; 9 public class ResponseDemo01 extends HttpServlet {One to ten private static final long Serialversionuid = 4312868947607 181532l;13 public void doget (HttpServletRequest request, httpservletresponse response) throws Servlet     Exception, IOException {outputchinesebyoutputstream (response);//Use OutputStream stream output Chinese    }18 19 /**20     * Use OutputStream stream to output Chinese     * @param request22     * @param response23 &NB Sp    * @throws ioexception */25 public void Outputchinesebyoutputstream (HttpServletResponse response) throws ioexception{26/** Use OutputStream output Chinese note:         * On the server side, the data is the Code table output, then control the clientThe browser opens with the appropriate code table,         * For example: Outputstream.write ("China". GetBytes ("UTF-8"));// Use OutputStream flow to the client browser output Chinese, UTF-8 encoding for output         * At this time to control the client browser to UTF-8 encoding open, otherwise display will appear in Chinese garbled, So how does the server side control the client browser to display the data in UTF-8 encoding?         * You can control browser behavior by setting the response header, for example:         * Response.setheader ("Content-type") , "Text/html;charset=utf-8");//By setting the response header control browser to display data in UTF-8 encoding */33 String data = "China"; outputstrea M outputstream = Response.getoutputstream ();//get OutputStream output stream to Response.setheader ("Content-type", "text/html;ch Arset=utf-8 ");//By setting the response header to control the browser to display data in UTF-8 encoding, if you do not add this sentence, then the browser will display garbled/**37         * Data.getbyte  S () is a process of converting a character into a byte array, which is sure to go to the Code table,         * If it is a Chinese operating system environment, the default is to find the Code table for GB2312, the number         * The process of converting a character to a byte array is to convert the Chinese characters to the corresponding number on the GB2312 's code table,         * For example: "Medium" the corresponding number on the GB2312 's code table is 9841   &NB Sp     *   &nbsp     "Country" the corresponding number on GB2312 's code table is 9942 */43/**44         * getBytes () method without parameters, the root According to the operating system's language environment to choose the Conversion Code table, if it is a Chinese operating system, then use the GB2312 Code table */46 byte[] Databytearr = data.getbytes ("UTF-8");//Convert characters to bytes Group, specifying UTF-8 encoding to convert outputstream.write (Databytearr);//Use OutputStream flow to client output byte array    }49 OID DoPost (httpservletrequest request, httpservletresponse response) Wuyi throws Servletexception, IOException {5 2        doget (request, response), +  }54 55}

The results of the operation are as follows:

  

After the client browser receives the data, it parses the data according to the character encoding set on the response header, as follows:

  

2.2, using PrintWriter flow to the client browser output Chinese data

Use PrintWriter stream to output Chinese note the problem:

Before getting the PrintWriter output stream, first use "Response.setcharacterencoding (CharSet)" To set the character to what encoding to output to the browser, such as: response.setcharacterencoding ("UTF-8"), set the character to "UTF-8" encoding output to the client browser, and then use Response.getwriter (); get PrintWriter output stream, These two steps cannot be reversed, as follows:

1 response.setcharacterencoding ("UTF-8");//Set the character to "UTF-8" encoding output to client browser 2/**3 * PrintWriter out = Response.getwriter (); This code must be placed in response.setcharacterencoding ("UTF-8"), followed by 4 * Otherwise response.setcharacterencoding ("UTF-8") This line of code will not be set, Browser display is still garbled 5 */6 printwriter out = Response.getwriter ();//get PrintWriter output stream

Then use Response.setheader ("Content-type", "text/html;charset= character encoding"), set the response header, control the browser to display with the specified character encoding encoding, for example:

1//By setting the response header control browser to UTF-8 encoding display data, if not add this sentence, then the browser will display is garbled 2 response.setheader ("Content-type", "Text/html;charset=utf-8") ;

In addition to using Response.setheader ("Content-type", "text/html;charset= character encoding"), and setting the response header to control the browser's display in the specified character encoding encoding, You can also simulate the action of the response head in the following ways

1/**2 * Learn a trick: Use the HTML language inside the <meta> tag to control browser behavior, simulation by setting the response header control browser behavior 3  *response.getwriter (). Write ("<meta http-equiv= ' Content-type ' content= ' text/html;charset=utf-8 '/> '); 4 * equivalent to Response.setheader ("Content-type", "text /html;charset=utf-8 "); 5 */6 Response.getwriter (). Write (" <meta http-equiv= ' content-type ' content= ' text/html; Charset=utf-8 '/> ");

Example: Using the PrintWriter to flow to the client browser output "China" two characters

 1 package gacl.response.study; 2 3 Import java.io.IOException; 4 Import Java.io.OutputStream; 5 Import Java.io.PrintWriter; 6 Import javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 One public class ResponseDemo01 extends HttpServlet {all private S Tatic final Long serialversionuid = 4312868947607181532l;14 public void doget (HttpServletRequest request, HTTPSERVL Etresponse response) throws Servletexception, IOException {outputchinesebyprintwriter (response); /use PrintWriter stream output chinese    }19/**21     * Use PrintWriter stream output chinese     * @param request     * @param response24     * @throws ioexception */26 public void Outputchinesebypri Ntwriter (HttpServletResponse response) throws ioexception{27 String data = "China"; 28 29//By setting the response header to control the UTF-8 is encoded in theThe data, if not added this sentence, then the browser will display is garbled ("Content-type", "Text/html;charset=utf-8");//response.setheader R Esponse.setcharacterencoding ("UTF-8");//settings output characters in "UTF-8" to client browser/**34         * Printwrite R out = Response.getwriter (); This code must be placed in response.setcharacterencoding ("UTF-8"), followed by         * Otherwise response.setcharacterencoding ("UTF-8") This line of code will not be set to be invalid, the browser display time is garbled */37 printwriter out = Response.getwrit ER ();//get PrintWriter output stream/**39         * Learn more: Use the <meta> tag inside the HTML language to control browser behavior and simulate the response header to control the Browser behavior         * Out.write ("<meta http-equiv= ' content-type ' content= ' text/html;charset=utf-8 '/& gt; ");                 * equivalent to Response.setheader ("Content-type", "Text/html;charset=utf-8"); 42 */43 Out.write ("<meta http-equiv= ' content-type ' content= ' text/html;charset=utf-8 '/> '); out.write (data);//Use PR Intwriter flow to client output characters   &NBSP;} DoPost public void (HttpServletRequest request, httpservletresponse response) throws Servletexc Eption, IOException {       doget (request, response),    }51}

When it is necessary to output character data to the browser, it is convenient to use printwriter, eliminating the step of converting characters to byte arrays.

2.3. Use OutputStream or printwriter to output numbers to the client browser

For example, there is the following code:

 1 package gacl.response.study; 2 3 Import java.io.IOException; 4 Import Java.io.OutputStream; 5 Import Java.io.PrintWriter; 6 7 Import Javax.servlet.ServletException; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11 public class     ResponseDemo01 extends HttpServlet {$ private static final Long Serialversionuid = 4312868947607181532l;15 16 public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep      tion {outputonebyoutputstream (response);//Use OutputStream output 1 to client browser   &NBSP;}22 23 /**24     * Using OutputStream stream output digital     * @param request26     * @param Response27 & nbsp   * @throws ioexception */29 public void Outputonebyoutputstream (HttpServletResponse response) throws IOE Xception{30 Response.setheader ("Content-type", "TeXt/html;charset=utf-8 "), OutputStream outputstream = Response.getoutputstream (), Outputstream.write (" Make          Output number 1 with OutputStream stream: ". GetBytes (" UTF-8 ")); 33outputstream.write (1);34}35 36}

Running the above code shows the following results:

  

The results of the operation and we imagined that the number 1 did not lose, the following we modify the above Outputonebyoutputstream method code, the modified code is as follows:

1     /** 2  * Output digital using OutputStream Stream 1 3  * @param request 4  * @param response 5  * @throws Ioex Ception  6      */7 public     void Outputonebyoutputstream (HttpServletResponse response) throws ioexception{8         Response.setheader ("Content-type", "Text/html;charset=utf-8"); 9         OutputStream outputstream = Response.getoutputstream (),         outputstream.write ("Use OutputStream stream output number 1:". GetBytes ("UTF-8"));         //outputstream.write (1);         Outputstream.write ((1+ ""). GetBytes ()); -     }

  1+ "" This step is to add the number 1 and an empty string, so that after processing, the number 1 becomes the string 1, and then convert the string 1 into a byte array using OutputStream for output, this time see the following results:

  

This time we can see the output of 1, this shows a problem: in the development process, if you want the server output what browser can see what, then the server side will be in the form of a string output .

If you are using the PrintWriter stream to output a number, convert the number to a string before outputting it, as follows:

1     /** 2  * Output digital using PrintWriter Stream 1 3  * @param request 4  * @param response 5  * @throws Ioexc Eption  6      */7 public     void Outputonebyprintwriter (HttpServletResponse response) throws ioexception{8         Response.setheader ("Content-type", "Text/html;charset=utf-8"); 9         response.setcharacterencoding ("UTF-8 ");         printwriter out = Response.getwriter ();//get PrintWriter output stream one by one         out.write (" use PrintWriter stream output number 1: "); 12         Out.write (1+ "");     

2.4. File download

File download function is often used in web development, the use of HttpServletResponse object can be used to achieve file download

The implementation of the file download function idea:

1. Get the absolute path to the file you want to download

2. Get the file name to download

3. Set the Content-disposition response header to control the browser to download the form of open file

4. Get the file input stream to download

5. Create a data buffer

6. Get the OutputStream stream from the response object

7. Writing the FileInputStream stream to buffer buffers

8. Using OutputStream to output buffer data to the client browser

Example: Using response for file download

 1 package gacl.response.study; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileReader; 5 Import java.io.IOException; 6 Import Java.io.InputStream; 7 Import Java.io.OutputStream; 8 Import Java.io.PrintWriter; 9 Import java.net.urlencoder;10 Import javax.servlet.servletexception;11 import javax.servlet.http.httpservlet;12 Import javax.servlet.http.httpservletrequest;13 Import javax.servlet.http.httpservletresponse;14/**15 * @author Gacl16 * File Download */18 public class ResponseDemo02 extends HttpServlet {$ public void doget (HttpServletRequest req Uest, HttpServletResponse response) throws Servletexception, IOException {downloadfilebyoutputstr EAM (response);//download file via OutputStream stream    }24/**26     * Download file via OutputStream stream,   &nbs P     * @param response28     * @throws FileNotFoundException29     * @throws IOException30 */31 private void DownloadFileByoutputstream (HttpServletResponse response) throws FileNotFoundException, IOException {33//1. Get to download         The absolute path of the file is Realpath String = This.getservletcontext (). Getrealpath ("/download/1.jpg"); 35//2. Gets the file name to download 36 String fileName = realpath.substring (realpath.lastindexof ("\ \") +1), 37//3. Set Content-disposition response header to control the browser-mounted shape         Open File Response.setheader ("Content-disposition", "Attachment;filename=" +filename), 39//4. Get the file input stream to download 40  InputStream in = new FileInputStream (realpath); int len = 0;42//5. Creating a data buffer [byte[] Buffer         = new byte[1024];44//6. Get OutputStream flow through response object OutputStream out = Response.getoutputstream (); 46 7. Write the FileInputStream stream to the buffer buffer (len = in.read (buffer)) > 0) {48//8. Use OutputStream to Buffer Area data output to client browser out.write (Buffer,0,len),        }51        in.clos E ();    }53 DoPost public void (HttpServletRequest request, httpservletresponse response) throws Servletexception , IOException {       doget (request, response);  }58}

The results of the operation are as follows:

  

Example: using response for Chinese file download

When downloading Chinese files, it is important to note that the Chinese file name is encoded using the Urlencoder.encode method (Urlencoder.encode (filename, "character encoding")), otherwise the file name will be garbled.

 1 package gacl.response.study; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileReader; 5 Import java.io.IOException; 6 Import Java.io.InputStream; 7 Import Java.io.OutputStream; 8 Import Java.io.PrintWriter; 9 Import java.net.urlencoder;10 Import javax.servlet.servletexception;11 import javax.servlet.http.httpservlet;12 Import javax.servlet.http.httpservletrequest;13 Import javax.servlet.http.httpservletresponse;14/**15 * @author Gacl16 * File Download */18 public class ResponseDemo02 extends HttpServlet {$ public void doget (HttpServletRequest req Uest, HttpServletResponse response) throws Servletexception, IOException {downloadchinesefilebyou Tputstream (response);//download Chinese files    }24/**26     * Download Chinese file, chinese file download, file name is URL encoded, otherwise the file name garbled 27 & nbsp   * @param response28     * @throws FileNotFoundException29     * @throws IOException30 * * -private void doWnloadchinesefilebyoutputstream (HttpServletResponse response) throws FileNotFoundException, IOException {33 String Realpath = This.getservletcontext (). Getrealpath ("/download/Zhangjiajie National Forest Park. JPG ");//Gets the absolute path of the file to be downloaded. String filename = realpath.substring (realpath.lastindexof (" \ \ ") +1);//Gets the file name to download 35/ /Set Content-disposition response header control browser to download the form of open file, Chinese file name to use the Urlencoder.encode method to encode, otherwise the file name garbled Response.setheader (" Content-disposition "," attachment;filename= "+urlencoder.encode (filename," UTF-8 ")); PNs InputStream in = new FILEINP  Utstream (Realpath);//get file input stream int len = 0;39 byte[] buffer = new byte[1024];40 outputstream out = Response.getoutputstream (); (len = in.read (buffer)) > 0) {out.write (Buffer,0,len); Data output of Flushing area to client browser        }44        in.close (),  }46   PU Blic void DoPost (HttpServletRequest request, HttpServletResponse RespoNSE) throws Servletexception, IOException {       doget (request, response), &nbsp ; &NBSP;}51}

The results of the operation are as follows:

  

File Download Note: It is recommended to use OutputStream stream when writing file download function, avoid using printwriter stream, because OutputStream stream is byte stream, can handle any kind of data, and PrintWriter stream is character stream. Only character data can be processed, and data loss can result if byte data is processed in a character stream.

Example: Using PrintWriter to download files

 1 package gacl.response.study; 2 Import Java.io.FileInputStream; 3 Import java.io.FileNotFoundException; 4 Import Java.io.FileReader; 5 Import java.io.IOException; 6 Import Java.io.InputStream; 7 Import Java.io.OutputStream; 8 Import Java.io.PrintWriter; 9 Import java.net.urlencoder;10 Import javax.servlet.servletexception;11 import javax.servlet.http.httpservlet;12 Import javax.servlet.http.httpservletrequest;13 Import javax.servlet.http.httpservletresponse;14/**15 * @author Gacl16 * File Download */18 public class ResponseDemo02 extends HttpServlet {$ public void doget (HttpServletRequest req Uest, HttpServletResponse response) throws Servletexception, IOException {Downloadfilebyprintwrit ER (response);//download file via PrintWriter stream    }24/**26     * Download file via PrintWriter stream, although it is also possible to download, but will result in data Lost, so it is not recommended to use PrintWriter stream to download files     * @param response28     * @throws FileNotFoundException29   & nbsp * @throws IOException30 */31 private void Downloadfilebyprintwriter (HttpServletResponse response) throws Filenotfoundexce Ption, IOException {realpath String = This.getservletcontext (). Getrealpath ("/download/Zhangjiajie National Forest Park. JPG ");//Gets the absolute path of the file to be downloaded. String filename = realpath.substring (realpath.lastindexof (" \ \ ") +1);//Gets the file name to download 35/ /Set Content-disposition response header control browser to download the form of open file, Chinese file name to use the Urlencoder.encode method to encode the Response.setheader (" Content-disposition "," attachment;filename= "+urlencoder.encode (filename," UTF-8 ")); PNs FileReader in = new FileRead ER (realpath); int len = 0;39 char[] buffer = new char[1024];40 printwriter out = Response.getwri ter (), in.read (len = (buffer)) > 0) {out.write (Buffer,0,len);//output buffer data to client browser &nbs P      }44        in.close ();    }46-public void DoPost (Httpserv    Letrequest request, httpservletresponse response) 48         Throws Servletexception, IOException {       doget (request, response),    }5 1}

The results of the operation are as follows:

  

Normal popup Download box, at this time we click the "Save" button to download the file, as follows:

  

As you can see, only 5.25MB is downloaded, and the original size of this picture is

  

This means that the data is lost at the time of download, so the download is incomplete, so the image can be downloaded normally, but it cannot be opened because some of the data has been lost, as shown below:

  

Therefore, it is important to note that using the PrintWriter stream to process byte data can result in data loss, so use the OutputStream stream when writing the download file function, avoiding the use of printwriter streams, because the OutputStream stream is a byte stream , you can handle any type of data, and the PrintWriter stream is a character stream that can handle only character data, which can result in data loss if the byte data is processed with a character stream.

Javaweb---Summary (vii) HttpServletResponse object (i)

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.