Response响应数据
1.1 响应字符数据
@WebServlet("/demo3")
public class Demo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;UTF-8");
PrintWriter writer = response.getWriter();
writer.write("<h1>我是中国人</h1>");
}
}
1.2 响应字节数据
@WebServlet("/demo4")
public class Demo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 响应字节数据
// 1. 从磁盘中写入图片
FileInputStream fis = new FileInputStream("/Users/mac/Downloads/Frame 15.gif");
// 2. 获取字节输出流
ServletOutputStream outputStream = response.getOutputStream();
//3. 写出图片
byte[] buff = new byte[1024];
int len = 0;
while((len = fis.read(buff))!= -1){
outputStream.write(buff,0,len);
}
fis.close();
}
使用commons-io工具
导入依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.9.0</version>
</dependency>
第3步的写出图片可以使用工具中提供的方法快速实现流的对拷
IOUtils.copy(fis,outputStream);