Java Web学习(七)HttpServletResponse(客户端响应)

本文借鉴:孤傲苍狼(特此感谢!)

一、定义

  HttpServletResponse对象代表服务端的响应,通过这个对象提供的方法,可以向客户机输出数据。

二、常用方法

PS:在JavaWeb开发中,只要是写URL地址,那么建议最好以"/"开头,也就是使用绝对路径的方式,如果"/"是给服务器用的,则代表当前的web工程,如果"/"是给浏览器用的,则代表webapps目录。

PS:也可以使用request.getContextPath()来代替"/项目名称"的方式,这样更加灵活。

    / ** 
         * 1 transmits data to the client (browser) 
         * Principle: the data written to the program ServletOutputStream Servlet or PrintWriter object to be retrieved from the response inside Servlet engine, Servlet engine data such as the body of the response message , and then outputs the response status in response to the first row and the combination of the client. 
         * PS: getOutputStream and getWriter these two methods are mutually exclusive , call any of these methods after, you can not call another method. 
         * PS: After Serlvet of service method, Servlet engine will check whether getWriter or output stream object getOutputStream method returns the close method has been called, and if not, Servlet engine will call the close method to close the output stream object.
         * / 
        OutputStream the outputStream = Response. The getOutputStream (); // Get OutputStream output stream (output binary data )
        . = Response OUT PrintWriter the getWriter (); // Get PrintWriter output stream (output text data ) / 

        ** 
         * Set 2. The head-related response (response header may be provided to control the behavior of a browser) 
         * / 
        . Response of setCharacterEncoding ( "UTF 8 "); // set the data" UTF-8 "encoded output to the client browser 
        Response. the setHeader Content-type", "text / HTML ("; charset = UTF-8 "); // control the browser display data to the UTF-8 encoding 
        response. setStatus (HttpServletResponse.SC_OK); // set of response codes 
        response. the setHeader ( "refresh", "5"); // control the browser is refreshed once every 5 seconds
        the Response. setContentType ( "Image / jpeg"); // tells the browser to handle this type of data (control of the browser to open the picture) 
        the Response. setDateHeader ( "expries", -1); // control the browser does not cache data 
        the Response. setHeader ( "cache-control", "nO-cache"); // control the browser does not cache the data 
        the Response. setHeader ( "Pragma", "nO-cache"); // control the browser does not cache data 

        / ** 
         * 3. redirect 
         * / 
        // method 1: call sendRedirect () method of 
        the Response. sendRedirect ( "redirect address");// redirection (internal implementation principle: setting response 302 using status codes and setting the location of redirect response headers)
         // Method 2: Set Location response header properties and status codes Status
        . Response the setHeader ( "the Location", "jump address"); // set the jump address 
        Response. setStatus (HttpServletResponse.SC_FOUND to); // set the status code 302, is equivalent to response.setStatus (302);

 

Third, resolve Detailed character (problems Chinese garbled)

/ ** 
 * server response (Chinese garbled) 
 * PS: During development, if you want server output what browser will be able to see anything, then the server should be output as a string (regardless of the output is character or numeric).
 * / 
Public  class ResponseDemo the extends the HttpServlet { 

    / ** 
     * output Chinese 
     * 
     * @param Response 
     * @throws IOException
      * / 
    public  void outputChinese (the HttpServletResponse Response) throws IOException { 

        String Data = "Chinese" ; 

        / ** 
         * 1. OutputStream flows to the client browser Chinese output data 
         * PS:服务器端可以通过设置响应头控制浏览器的行为
         * 例:设置响应头控制浏览器以UTF-8的编码显示数据:response.setHeader("content-type", "text/html;charset=UTF-8");
         */
        byte[] dataByteArr = data.getBytes("UTF-8");//将字符转换成字节数组,指定以UTF-8编码进行转换(将字符转换成字节数组的过程,这个过程中一定会去查码表,如果是中文的操作系统环境,默认就是查找查GB2312的码表)
        OutputStream outputStream = response.getOutputStream();//获取OutputStream输出流
        response.setHeader("content-type", "text/html;charset=UTF-8");//通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
        outputStream.write(dataByteArr);//使用OutputStream流向客户端输出字节数组

        /**
         * 2.使用PrintWriter流向客户端浏览器输出中文数据
         * PS:When you need to output character data to the browser, use PrintWriter more convenient, eliminating the need to convert the characters into a byte array that step.
         * / 
        Response.setCharacterEncoding ( "UTF-8"); // set to output the character "UTF-8" to the client browser encoding 
        PrintWriter response.getWriter OUT = (); // Get PrintWriter output stream ( the PS: This sentence code must be placed response.setCharacterEncoding ( "UTF-8"); after, otherwise response.setCharacterEncoding ( "UTF-8") set up this line of code will not work, the browser displays the time or garbled) 
        response.setHeader ( " type-Content "," text / HTML; charset = UTF-. 8 "); // set the response header to specify the control of the browser displays character coding 
        out.write (Data); // use client output flow PrintWriter characters 
    } 

}

 

Fourth, the file download

PS: Recommended time of writing file download function using OutputStream stream, avoiding the use of PrintWriter stream, because OutputStream stream is a stream of bytes, can handle any type of data, and PrintWriter stream is a stream of characters, can only deal with character data, if a character stream processing bytes of data will result in data loss.

   / ** 
     * download files through OutputStream stream 
     * @param the Response 
     * @throws FileNotFoundException 
     * @throws IOException
      * / 
    Private  void downloadFileByOutputStream (HttpServletResponse the Response)
             throws FileNotFoundException, IOException {
         // 1. Download the file to get the absolute path 
        String realPath = the this .getServletContext () getRealPath ( "/ download / 1.JPG." );
         // 2. get to download the file name 
        String fileName = realPath.substring (realPath.lastIndexOf ( "\\") + 1 );
         / /3.设置content-disposition响应头控制浏览器以下载的形式打开文件(PS:中文文件名的情况要使用URLEncoder.encode方法进行编码:response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));)
        response.setHeader("content-disposition", "attachment;filename="+fileName);
        //4.获取要下载的文件输入流
        InputStream in = new FileInputStream(realPath);
        int len = 0;
        //5.创建数据缓冲区(一次读取1024个字节)
        byte[] buffer = new byte[1024];
        //6.通过response对象获取OutputStream流
        OutputStream out =response.getOutputStream ();
         // 7. The buffer is written to the stream buffer FileInputStream 
        the while ((len = in.read (buffer))> 0 ) {
         // 8. The use OutputStream output data buffer to the client browser 
            out.write (Buffer, 0 , len); 
        } 
        in.close (); 
    }

 

Guess you like

Origin www.cnblogs.com/riches/p/11413798.html