JavaWeb篇_11——HttpServletResponse对象

本文介绍了如何在Java中使用HttpServletResponse对象进行响应设置,包括字符型响应(如HTML、文本和JSON)、字节型响应(如图片),以及重定向响应和文件下载,同时处理中文文件名的编码问题。
摘要由CSDN通过智能技术生成

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("<!DOCTYPE html>");
       pw.println("<html lang=en>");
       pw.println("<head>");
       pw.println("<meta charset=UTF-8>");
       pw.println("<title>Document</title>");
       pw.println("</head>");
       pw.println("<body>");
       pw.println("<font color=blue>HelloWorld</font>");
       pw.println("</body>");
       pw.println("</html>");
       pw.flush();
       pw.close();
   }
}

<servlet>
        <servlet-name>responseCharacterServlet</servlet-name>
        <servlet-class>com.java.ResponseCharacterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>responseCharacterServlet</servlet-name>
        <url-pattern>/character.do</url-pattern>
    </servlet-mapping>
设置字节型响应

常见的字节型响应:

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();

   }
}

	<servlet>
        <servlet-name>responseByteServlet</servlet-name>
        <servlet-class>com.java.ResponseByteServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>responseByteServlet</servlet-name>
        <url-pattern>/byte.do</url-pattern>
    </servlet-mapping>

设置响应编码

设置响应编码有两种方式

  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/");

   }
    <servlet>
        <servlet-name>redirectServlet</servlet-name>
        <servlet-class>com.java.RedirectServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>redirectServlet</servlet-name>
        <url-pattern>/redirect.do</url-pattern>
    </servlet-mapping>
文件下载

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

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

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();
   }
}
    <servlet>
        <servlet-name>fileDownServlet</servlet-name>
        <servlet-class>com.java.FileDownServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>fileDownServlet</servlet-name>
        <url-pattern>/fileDown.do</url-pattern>
    </servlet-mapping>
解决文件名中文乱码问题
resp.addHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("gbk"),"iso-8859-1"));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值