一、预览
介绍完Servlet-Resquest的相关内容后,接下来就是Servlet- Response的内容。读者阅读完本篇文章后将可以自如地解析请求、设置响应,完成对客户端的响应。
二、Response体系结构
Response的体系结构与Request完全一样,其中ServletResponse与HttpServletResponse都是Java官方定义的接口,ResponseFacade是Web服务器(Tomcat)的实现类。
三、常用API
Response响应分为响应字符数据与响应字节数据。
(1)字符响应
package com.byhuang.response;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 响应字符数据:设置字符数据的响应体
*/
@WebServlet("/res2")
public class ResponseDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("res2...");
System.out.println(resp.getContentType());
// 数据格式 以及 编码格式
resp.setContentType("text/html;charset=utf-8");
// 1 获取字符输出流
PrintWriter writer = resp.getWriter();
writer.write("<h1>aaa</h1>");
// 流不需要关闭
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
(2)字节响应
package com.byhuang.response;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 响应字节数据:设置字节数据的响应体
*/
@WebServlet("/res3")
public class ResponseDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("res3...");
FileInputStream fileInputStream = new FileInputStream("/Users/huangbingyi/Desktop/pic.png");
ServletOutputStream outputStream = resp.getOutputStream();
IOUtils.copy(fileInputStream, outputStream);
fileInputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}