响应字符数据:
@WebServlet("/servletDemo3")
public class HttpServletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应编码格式
resp.setContentType("text/html;charset=UTF-8");
//获取字节输出流
ServletOutputStream os = resp.getOutputStream();
//写数据
os.write("你好".getBytes("UTF-8"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
响应图片:
@WebServlet("/servletDemo3")
public class HttpServletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取图片绝对路径
String realPath = getServletContext().getRealPath("/img/1.png");
System.out.println(realPath);
//1、获取字节输出流
ServletOutputStream os = resp.getOutputStream();
//2、创建字节输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
//3、读取图片并写出
int len;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
bis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}