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);//using OutputStream stream output Chinese 17}18 19/**20 * Use OutputStream Stream output Chinese * @param request22 * @param response23 * @throws IOException 24 */25 public void Outputchinesebyoutputstream (HttpServletResponse response) throws ioexception{26/** use OutputStream output Chinese note The question: 27 * On the server side, the data is the Code table output, then control the client browser with the corresponding Code table open, 28 * For example: Outputstream.write ("China". GetBytes ("UTF-8"))///Use OutputStream flow to the client browser to output Chinese, output in UTF-8 encoding 29 * At this time to control the client browser to UTF-8 encoding open, otherwise display will appear when the Chinese garbled, then the server side how to control the client browser to utf- 8 of the code shows the data? 30 * You can control the behavior of the browser by setting the response header, for example: * Response.setheader ("Content-type", "text/html;charset=utf-8");//By setting the response header control The browser displays the data in UTF-8 encoding */33 String data = "China"; outputstream outputstream = Response.getoutputstrea m ();//get OutputStream output stream Response.setheader ("Content-type", "text/html;charset=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 is garbled/**37 * data.getbytes () is a character into a byte array of the process, the process will certainly go to check the Code table, 38 * If it is a Chinese operating system environment, the default is to find the GB2312 code table, 39 * The process of converting characters to byte arrays is to convert the Chinese character to the corresponding number 40 on the GB2312 code table * For example: "Medium" in GB2312 The corresponding number on the code table is 9841 * "Country" the corresponding number on the GB2312 's Code table is 9942 */43/**44 * getBytes () method if without parameters, it will be based on Operating system language environment to choose the Conversion Code table, if it is a Chinese operating system, then use GB2312 Code table */46 byte[] Databytearr = data.getbytes ("UTF-8");//convert character to byte array , specifying the conversion of OutputStream with UTF-8 encoding.Write (Databytearr);//use OutputStream to flow to the client output byte array}49 public void DoPost (HttpServletRequest request, HttpServlet Response Response) Wuyi throws Servletexception, IOException {doget (request, Response); 53}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 18}19 20/**21 * Output with PrintWriter stream Chinese * @param request23 * @param response24 * @throws ioexception */26 public void Outputchinesebyprintwriter (HttpServletResponse response) throws Ioex ception{27 String data = "China"; 28 29//By setting the response header control browser to display data in UTF-8 encoding, if you do not add this sentence, then the browser will display is garbled//r Esponse.sethEader ("Content-type", "Text/html;charset=utf-8"); Response.setcharacterencoding ("UTF-8");//Set the character to "UTF -8 "encoded output to client browser/**34 * PrintWriter out = Response.getwriter (); This code must be placed in response.setcharacterencoding (" UT F-8 "); after 35 * Otherwise response.setcharacterencoding (" UTF-8 ") This line of code will be invalid, the browser display time is garbled */37 PrintWriter out = Response.getwriter ();//get PrintWriter output Stream 38/**39 * Learn a trick: Use the HTML language <meta> tags to control browser behavior, simulation by setting the response header control Browser Behavior Out.write * ("<meta http-equiv= ' content-type ' content= ' text/html;charset=utf-8 '/> '); 41 * etc Same as Response.setheader ("Content-type", "Text/html;charset=utf-8"); */43 out.write ("<meta http-equiv=" C Ontent-type ' content= ' text/html;charset=utf-8 '/> '); out.write (data);//use PrintWriter flow to client output characters 45}46 47 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, I oexception {DOget (request, response); 50}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 20 21}22 23/**24 * Use OutputStream Stream output Digital * @param request26 * @param response27 * @throws IOException 28 */29 public void Outputonebyoutputstream (HttpServletResponse response) throws ioexception{30 Response.setheader ("cont Ent-type "," Text/html;charset=utf-8 "); OutputStream ouTputstream = Response.getoutputstream (); Outputstream.write ("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 IOException 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 IOException 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 11 out.write ("output number 1 with PrintWriter stream"); 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 23}24 25/**26 * Download file via outputstream stream * @param response28 * @throws FileNotFoundException29 * @throws IOException30 */31 private void Downloadfilebyoutputstream (Httpser Vletresponse response) 32 Throws FileNotFoundException, IOException {33//1. Gets the absolute path of the file to download. String Realpath = THIS.GETSERVL Etcontext (). Getrealpath ("/download/1.jpg"); 35//2. Gets the filename to download. String filename = realpath.substring (realpat H.lastindexof ("\ \") +1); 37//3. Setting the Content-disposition response header to control the browser to download the form of open file Response.setheader ("Content-dispos Ition "," attachment;filename= "+filename); 39//4. Gets the file input stream to download. InputStream in = new FileInputStream (realpat h); int len = 0;42//5. Create data buffer byte[] buffer = new byte[1024];44//6. Get out by Response object Putstream stream OutputStream out = Response.getoutputstream (); 46//7. Writing FileInputStream stream to buffer buffers 47 while (len = in.read (buffer)) > 0) {48//8. Use OutputStream to output buffer data to client browser out.write (Buffer,0,len );}51 in.close ();}53 the public void DoPost (HttpServletRequest request, HttpServletResponse R Esponse) THrows servletexception, IOException {doget (request, response); 57}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 file 23}24 25/**26 * Download Chinese file, chinese file download, file name is URL encoded, otherwise the file name will appear garbled * @param response * @throws FileNotFoundException29 * @throws IOException30 */31 private void Downloadchinesefilebyout Putstream (httpservletresponsE response) throws FileNotFoundException, IOException {$ 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); The data of the flushing zone is output to the client browser}44 in.close ();}46 public void DoPost (HttpServletRequest request, HttpS Ervletresponse response) throws Servletexception, IOException {doget (request, response); 50}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 23}24 25/**26 * Download file via PrintWriter stream, although it is also possible to download, but will result in data loss, so it is not recommended to use Printwrite R Stream Download File * @param response28 * @throws FileNotFoundException29 * @throws IOException30 */31 privat e void DOWNLOADFILEBYPRINTWRITER (HttpServletResponse response) throws FileNotFoundException, IOException {$ realpath = t His.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 43 }44 in.close ();}46 public void DoPost (HttpServletRequest request, HttpServletResponse respons E) throws Servletexception, IOException {doget (request, response); 50}51}
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.
HttpServletResponse Object (i)