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("<!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"));
posted @ 2023-11-15 16:09  Gjq-  阅读(34)  评论(0编辑  收藏  举报  来源