• JavaWeb篇_11——HttpServletResponse对象


    HttpServletResponse对象

    HttpServletResponse对象代表服务器的响应。这个对象中封装了响应客户端浏览器的流对象,以及向客户端浏览器响应的响应头、响应数据、响应状态码等信息。

    设置响应类型

    resp.setContentType("MIME")

    该方法可通过MIME-Type设置响应类型。

    TypeMeaning
    application/mswordMicrosoft Word document
    application/octet-streamUnrecognized or binary data
    application/pdfAcrobat (.pdf) file
    application/postscriptPostScript file
    application/vnd.lotus-notesLotus Notes file
    application/vnd.ms-excelExcel spreadsheet
    application/vnd.ms-powerpointPowerPoint presentation
    application/x-gzipGzip archive
    application/x-java-archiveJAR file
    application/x-java-serialized-objectSerialized Java object
    application/x-java-vmJava bytecode (.class) file
    application/zipZip archive
    application/jsonJSON
    audio/basicSound file in .au or .snd format
    audio/midiMIDI sound file
    audio/x-aiffAIFF sound file
    audio/x-wavMicrosoft Windows sound file
    image/gifGIF image
    image/jpegJPEG image
    image/pngPNG image
    image/tiffTIFF image
    image/x-xbitmapX Windows bitmap image
    text/cssHTML cascading style sheet
    text/htmlHTML document
    text/plainPlain text
    text/xmlXML
    video/mpegMPEG video clip
    video/quicktimeQuickTime video clip
    设置字符型响应

    常见的字符型响应类型:

    resp.setContentType("text/html")

    设置响应类型为文本型,内容含有html字符串,是默认的响应类型

    resp.setContentType("text/plain")

    设置响应类型为文本型,内容是普通文本。

    resp.setContentType("application/json")

    设置响应类型为JSON格式的字符串。

    /**
    * 设置字符型响应
    */
    public class ResponseCharacterServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doPost(req,resp);
       }
    
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //设置字符型响应类型
           resp.setContentType("text/html");
    
           PrintWriter pw = resp.getWriter();
           pw.println("");
           pw.println("");
           pw.println("");
           pw.println("");
           pw.println("Document");
           pw.println("");
           pw.println("");
           pw.println("HelloWorld");
           pw.println("");
           pw.println("");
           pw.flush();
           pw.close();
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    <servlet>
            <servlet-name>responseCharacterServletservlet-name>
            <servlet-class>com.java.ResponseCharacterServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>responseCharacterServletservlet-name>
            <url-pattern>/character.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    设置字节型响应

    常见的字节型响应:

    resp.setContentType("image/jpeg")

    设置响应类型为图片类型,图片类型为jpeg或jpg格式。

    resp.setContentType("image/gif")

    设置响应类型为图片类型,图片类型为gif格式。

    /**
    * 产生字节类型响应
    */
    public class ResponseByteServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doPost(req,resp);
       }
    
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
           //给定读取响应图片的路径
           File file=new File("C:\\Users\\HX\\Desktop\\详细安排.PNG");
           //创建读取图片的IO流
           InputStream is=new FileInputStream(file);
           //创建字节缓冲区
           byte[] buff=new byte[is.available()];
           //读取响应图片
           is.read(buff);
    
           //设置响应类型
           resp.setContentType("image/png");
           //产生字节类型响应
           OutputStream outputStream = resp.getOutputStream();
           outputStream.write(buff);
           outputStream.flush();
           outputStream.close();
    
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    	<servlet>
            <servlet-name>responseByteServletservlet-name>
            <servlet-class>com.java.ResponseByteServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>responseByteServletservlet-name>
            <url-pattern>/byte.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    设置响应编码

    设置响应编码有两种方式

    1. response.setContentType("text/html; charset=UTF-8");
    2. response.setCharacterEncoding("UTF-8");

    response.setContentType("text/html;charset=utf-8");

    不仅发送到浏览器的内容会使用UTF-8编码,而且还通知浏览器使用UTF-8编码方式进行显示。所以总能正常显示中文

    response.setCharacterEncoding("utf-8");

    仅仅是发送的浏览器的内容是UTF-8编码的,至于浏览器是用哪种编码方式显示不管。 所以当浏览器的显示编码方式不是UTF-8的时候,就会看到乱码,需要手动指定浏览器编码。

    在响应中添加附加信息

    重定向响应

    response.sendRedirect(URL地址)

    重定向响应会在响应头中添加一个Location的key对应的value是给定的URL。客户端浏览器在解析响应头后自动向Location中的URL发送请求。

    重定向响应特点:

    1. 重定向会产生两次请求两次响应。
    2. 重定向的URL是由客户端浏览器发送的。
    3. 浏览器地址栏会有变化。
    /**
    * 重定向响应
    */
    public class RedirectServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doPost(req,resp);
       }
    
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           resp.sendRedirect("https://www.baidu.com/");
    
       }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
        <servlet>
            <servlet-name>redirectServletservlet-name>
            <servlet-class>com.java.RedirectServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>redirectServletservlet-name>
            <url-pattern>/redirect.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    文件下载

    在实现文件下载时,我们需要在响应头中添加附加信息。

    response.addHeader("Content-Disposition", "attachment; filename="+文件名);
    
    • 1

    Content-Disposition:attachment

    该附加信息表示作为对下载文件的一个标识字段。不会在浏览器中显示而是直接做下载处理。

    filename=文件名

    表示指定下载文件的文件名。

    /**
    * 文件下载
    */
    public class FileDownServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doPost(req, resp);
       }
    
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           File file=new File("C:\\Users\\HX\\Desktop\\详细安排.PNG");
           InputStream is=new FileInputStream(file);
           byte[] buff=new byte[is.available()];
           is.read(buff);
    
           //在响应中添加附加信息
           resp.addHeader("Content-Disposition","attachment;filename="+file.getName());
    
           //产生响应
           ServletOutputStream outputStream = resp.getOutputStream();
           outputStream.write(buff);
           outputStream.flush();
           outputStream.close();
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
        <servlet>
            <servlet-name>fileDownServletservlet-name>
            <servlet-class>com.java.FileDownServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>fileDownServletservlet-name>
            <url-pattern>/fileDown.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    解决文件名中文乱码问题
    resp.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("gbk"),"iso-8859-1"));
    
    • 1
  • 相关阅读:
    【谢希尔 计算机网络】第4章 网络层
    【韩顺平】Linux基础
    Linux 中的 cd 命令及示例
    dom-to-image库是如何将html转换成图片的
    k8s详细安装过程
    快速掌握jmeter(二)——控制器与beanshell实现csv自动化测试模板
    实战模拟│企业微信机器人实时报错预警
    1688全店商品采集教程,1688店铺所有商品接口(详解1688店铺所有商品数据采集步骤方法和代码示例)
    yolo系列面试题
    Java实训:学生信息管理系统
  • 原文地址:https://blog.csdn.net/guojiaqi_/article/details/134422611